www.jetdv.com Forum Index Edward Troxel
Vegas Scripting and Newsletters
Home of Excalibur and Montage Magic
 
 FAQ   Search   Memberlist   Usergroups   Register   Profile 
 Log in to check your private messagesLog in to check your private messages   Log inLog in 

Covert Directory + Batch Render GUI - ALL IN ONE

 
Post new topic   Reply to topic    www.jetdv.com Forum Index -> Free Scripts
View previous topic :: View next topic  
Author Message
tonygil



Joined: 05 Jun 2010
Posts: 1

PostPosted: Mon Jun 07, 2010 6:02 pm    Post subject: Covert Directory + Batch Render GUI - ALL IN ONE Reply with quote

im currently working on a script that allows you to convert all video files (of a given type - in this case MTS AVCHD) in a directory, using John Meyer's Batch Render GUI interface.

therefore, you can convert multiple files using multiple renderers and templates.

if anyone cares to help me, i need to change the folder BROWSE routine (im using file search, but it works.

anyone care to comment / help / use:

www.1filmes.com.br/vegas/ConvertMTSFolderMultiTemplatesGUI.rar


Code:
/**
 * Script for converting MTS video files to other formats
 * that performs batch renders with GUI for selecting
 * render templates.
 *
 * user chooses a folder and all MTS video files there will be converted
 * and placed in unique timestamped folders tagged with renderer + template name
 * NOTE: i find the file format used by most batch renderers to be sloppy and creates extra work
 *
 * adapted from JHM's region render script + wil's CHP chapetr files creation
 * script
 *
 * Creation Date: Mar. 25, 2003.
 * Reivsed by JHM November 23, 2003
 
 * adapted by TG on June 6, 2010

 **/
import System;
import System.Collections;
import System.Text;
import System.IO;
import System.Drawing;
import System.Windows.Forms;
import Sony.Vegas;

// set this to true if you want to allow files to be overwritten
var overwriteExistingFiles = true;

// The inputFileRegexp is used to filter the input files. Only those
// whose file name matches using this regular expression will be
// converted. The following will match all files the end with MTS
// (ignoring case):
var inputFileRegexp = /.mts$/i;

// This version will match all input files.
//var inputFileRegexp = /.*/;

////MessageBox.Show ("ok 01");


//----------------------------------------------------------------------------------------
// Form subclass that is the dialog box for this script

class getFnameDialog extends Form {
    var browseButton;
    var fileNameBox;
   var noticeBox;
   

//----------------------------------------------------------------------------------------
// Button subclass that shows a save file dialog when clicked

class BrowseButton extends Button {
    var myResultBox = null;

    function BrowseButton(resultBox) {
       myResultBox = resultBox;
    }

    protected override function OnClick(e : EventArgs) {
      var desDir = "F:\\home\\dv\\apps\\spruce\\dvdmaestro\\chp";
      var srcMpgFname = "*.mts";
      var desExt = ".mts";
      var desFullFname = desDir + Path.DirectorySeparatorChar + srcMpgFname;


        var saveFileDialog = new SaveFileDialog();
      saveFileDialog.Filter = "MTS Video Files (*.mts)|*.mts|All Files (*.*)|*.*";
      saveFileDialog.DefaultExt = desExt;
        saveFileDialog.CheckPathExists = true;
      saveFileDialog.CheckFileExists = false;
      saveFileDialog.AddExtension = false;
        if (null != myResultBox) {
            var filename = myResultBox.Text;
            var initialDir = Path.GetDirectoryName(filename);
            if (Directory.Exists(initialDir)) {
                saveFileDialog.InitialDirectory = initialDir;
         }
         // tg marked this as comment to test how to get directory without file
            saveFileDialog.FileName = Path.GetFileNameWithoutExtension(filename);
//         saveFileDialog.FileName = Path.GetFileName(filename);


        }

        if ( System.Windows.Forms.DialogResult.OK == saveFileDialog.ShowDialog() ) {
            if ( null != myResultBox ) {
            if ( Path.GetExtension(saveFileDialog.FileName) != desExt ) {
               saveFileDialog.FileName = Path.GetFileNameWithoutExtension(saveFileDialog.FileName);
               saveFileDialog.FileName += desExt;
            }
            // myResultBox.Text = Path.GetFullPath(saveFileDialog.FileName);
            var tmpResultBoxtext = Path.GetFullPath(saveFileDialog.FileName);
            var tmpResultBoxDir = Path.GetDirectoryName(tmpResultBoxtext);
            ////MessageBox.Show (tmpResultBoxtext + " - "  + tmpResultBoxDir);
            myResultBox.Text = Path.GetDirectoryName(tmpResultBoxtext);
            }
        }
    }
}

    function getFnameDialog(baseFileName) {

        this.Text = "Convert MTS files in directory to new format video";
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.StartPosition = FormStartPosition.CenterScreen;
        this.Width = 580;

        var buttonWidth = 80;

      fileNameBox = addTextControl("Original MTS files folder", 6, 480, 10, baseFileName);
      noticeBox = addTextLabel("Caution: please choose folder that EXISTS", 6, fileNameBox.Bottom+5);

        browseButton = new BrowseButton(fileNameBox);
        browseButton.Left = fileNameBox.Right + 4;
        browseButton.Top = fileNameBox.Top - 2;
        browseButton.Width = buttonWidth;
        browseButton.Height = browseButton.Font.Height + 12;
        browseButton.Text = "Browse...";
        Controls.Add(browseButton);

        var buttonTop = noticeBox.Bottom + 16;

        var okButton = new Button();
        okButton.Text = "OK";
        okButton.Left = this.Width - (2*(buttonWidth+10));
        okButton.Top = buttonTop;
        okButton.Width = buttonWidth;
        okButton.Height = okButton.Font.Height + 12;
        okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
        AcceptButton = okButton;
        Controls.Add(okButton);

        var cancelButton = new Button();
        cancelButton.Text = "Cancel";
        cancelButton.Left = this.Width - (1*(buttonWidth+10));
        cancelButton.Top = buttonTop;
        cancelButton.Height = cancelButton.Font.Height + 12;
        cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        CancelButton = cancelButton;
        Controls.Add(cancelButton);

        var titleHeight = this.Height - this.ClientSize.Height;
        this.Height = titleHeight + okButton.Bottom + 8;
    }

   function addTextLabel(labelName, left, top) {
      var label = new Label();

      label.AutoSize = true;
      label.Text = labelName;
      label.Left = left;
      label.Top = top + 4;
      Controls.Add(label);
      return label;
   }

   function addTextControl(labelName, left, width, top, defaultValue) {
      var label = new Label();
      label.AutoSize = true;
      label.Text = labelName + ":";
      label.Left = left;
      label.Top = top + 4;
      Controls.Add(label);

      var textbox = new TextBox();
      textbox.Multiline = false;
      textbox.Left = label.Right;
      textbox.Top = top;
      textbox.Width = width - (label.Width);
      textbox.Text = defaultValue;
      Controls.Add(textbox);

      return textbox;
   }
}



try {


        // create a new project with one video track and one audio track.
       var proj = new Project();
      var videoTrack = new VideoTrack();
       proj.Tracks.Add(videoTrack);
       var audioTrack = new AudioTrack();
       proj.Tracks.Add(audioTrack);


   // default variables for the GUI.
    var defaultBasePath : String = Vegas.Project.FilePath;
    if ((null == defaultBasePath) || (0 == defaultBasePath.length)) {
        defaultBasePath = "C:\Temp_";
    } else {
        var dir = Path.GetDirectoryName(defaultBasePath);
        var fileName = Path.GetFileNameWithoutExtension(defaultBasePath);
        defaultBasePath = dir + Path.DirectorySeparatorChar + fileName + "_";
    }

    var dlog = new BatchRenderDialog();
    if (DialogResult.OK == dlog.ShowDialog()) {
        var selectedTemplates = dlog.GetCheckedTemplates();
        // inform the user of some special failure cases
        if (0 == selectedTemplates.Count)
            throw "no render templates selected";
        var outputFilePath = dlog.fileNameBox.Text;
        var renderMode = RenderMode.Project;
        if (dlog.renderRegions.Checked) {
            renderMode = RenderMode.Regions;
        } else if (dlog.renderSelection.Checked) {
            renderMode = RenderMode.Selection;
        }
        var renderSelection = dlog.renderSelection.Checked;
       
      
      // insert code for convert mts
      DoBatchRender(selectedTemplates, outputFilePath, renderMode);
      
      
      
    }
} catch (e) {
    if (!e.skipMessageBox)
        MessageBox.Show(e);
}

enum RenderMode {
    Project = 0,
    Selection,
    Regions,
}

function DoBatchRender(selectedTemplates : ArrayList,
                       basePath : String,
                       renderMode : RenderMode)
{
    var outputDirectory = Path.GetDirectoryName(basePath);
    var baseFileName = Path.GetFileName(basePath);
 
    // check if the base output directory exists
    /**if (!Directory.Exists(outputDirectory))
    {
        var msg = new StringBuilder("The output directory (");
        msg.Append(outputDirectory);
        msg.Append(") does not exist.\n");
        msg.Append("Please specify directory and base file name using the Browse button.");
        throw msg;
    }
   **/
    var zero : int = 0;
   
   // files will be created in unique folders inside the intput directory
   // the folder names will be [timestamp YYYYMmmDD_HH:MM + renderer + renderTemplate]
   // timestamp will be the time of the beginning of the batch job
   // and will be the same for all templates
   // therefore, it must be calculated outside the TEMPLATE ARRAY LOOP
   
   var today = new Date();
   var ObjDate = today.toTimeString();
   var tmpTimestamp = today.toString();
   var tmpTimestampLength = tmpTimestamp.length - 4;
   var tmpTimestampYear = tmpTimestamp.substring(tmpTimestampLength);
   var tmpTimestampMonth = tmpTimestamp.substring(4, 7);

   // clear DATESTRING and leave
   // only DAY [may be 1 or 2 digits]
   // find 1st ":" (colon) string in date and remove 3 digits
   var tmpSearchString = /:/;
   var tmpDateEnd = tmpTimestamp.search(tmpSearchString);
   var tmpTimestampDay = tmpTimestamp.substring(8, tmpDateEnd-3);
   var tmpTimestampHour = today.toTimeString().substring(0,5);
   
   // partial output folder name = timestamp [YYYYMmmDD_HH:MM]
   var tmpTimestampFolderName = tmpTimestampYear + tmpTimestampMonth + tmpTimestampDay + "_" + tmpTimestampHour + "_";
   //MessageBox.Show(" timestamp: "  + tmpTimestampFolderName);
   
   // check if any invalid characters are present
   var tmpFileName2Check = tmpTimestampFolderName;
   tmpTimestampFolderName = FixFileName(tmpFileName2Check);
   //MessageBox.Show(tmpFileName2Check + " checou e corrigiu: " + tmpTimestampFolderName);
   
   // insert call to dialog that gets folder where MTS files are
   // TG 20100606
   
   // Variables
   //

   var formatMsg = "unknown";
   var originalProjectRuler = Vegas.Project.Ruler.Format;
   
      var frameRate = Vegas.Project.Video.FrameRate;

      if ( frameRate == 25 ) {
      formatMsg = "PAL, 25fps";
//      //MessageBox.Show(formatMsg);
      Vegas.Project.Ruler.Format = RulerFormat.SmpteEBU;
   }
   else {
      formatMsg = "NTSC, 29.97fps, TC=non-drop-frame";
//      //MessageBox.Show(formatMsg);
      Vegas.Project.Ruler.Format = RulerFormat.SmpteNonDrop;
   }

   // Show the script's dialog box.
   var srcMpgFname = ".mts";
   var dialog = new getFnameDialog(srcMpgFname);
   var dialogResult = dialog.ShowDialog();
   
// The inputDirectory variable specifies where the rendered files will
// be created (do not include the trailing back-slash)
var inputDirectory = dialog.fileNameBox.Text;

// The outputDirectory variable specifies where the rendered files
// will be created (do not include the trailing back-slash)
// var outputDirectory = dialog.fileNameBox.Text + templateRegexp;
//
// all converted files will be stored in folders inside the INPUT folder
// change at will (say, in case disk is full)
var outputDirectory = inputDirectory;

// alternative destination is BESIDE the INPUTFOLDER in a FOLDER called CONVERT01
// var outputDirectory = inputDirectory.substring(0,inputDirectory.lastIndexOf(Path.DirectorySeparatorChar)+1) + "convert01";

//MessageBox.Show(outputDirectory + " - " + inputDirectory  + " = " + inputDirectory.lastIndexOf(Path.DirectorySeparatorChar));
//MessageBox.Show(inputDirectory + outputDirectory);

   
   
    var zeroTime = new Timecode();
    var renderStart, renderLength;

    var templateFound = false;

    // enumerate through each selected render template
    var selections = new Enumerator(selectedTemplates);
   var counterDirectory = 1;
    while (!selections.atEnd()) {
        var tag = selections.item();
        var renderer = tag.renderer;      
      // erro de tipo
      var tmpRendererName = renderer.Name;
      tmpRendererName = tmpRendererName.substring(0,10) + "_" + renderer.FileExtension.substring(2);
        var renderTemplate = tag.template;
      
      // var tmpRendererNameLength = tmpRendererName.length;
      // var tmpRendererType = tmpRendererName.substring(tmpRendererNameLength-4,tmpRendererNameLength-1)

      var tmpFolderName = tmpTimestampFolderName + tmpRendererName + "_" + renderTemplate;
      var outputDirectoryRenderTemplate = outputDirectory + "\\" + tmpFolderName + counterDirectory;
      //MessageBox.Show("folder: " + outputDirectoryRenderTemplate);
      outputDirectoryRenderTemplate = FixFolderName(outputDirectoryRenderTemplate);
      //MessageBox.Show("saiu FixFileName" + outputDirectoryRenderTemplate);      
      if (!Directory.Exists(outputDirectoryRenderTemplate))
       {
           // var msg = new StringBuilder("The output directory (");
           // msg.Append(outputDirectory);
           // msg.Append(") does not exist.\n");
           // msg.Append("Please edit the script to specify an existing directory.");
           // throw msg;
         //MessageBox.Show("entrou cria folder: " + outputDirectoryRenderTemplate.length);      
         
         Directory.CreateDirectory(outputDirectoryRenderTemplate);
         var tmpDirectoryCreatedByJob = new Boolean (1);


       } else {
         
         //if tmpDirectoryCreatedByJob
         
         
            /**
            while (!tmpDirectoryCreatedByJob && Directory.Exists(outputDirectoryRenderTemplate)) {
            var msg = new StringBuilder("The output directory (");
              msg.Append(outputDirectoryRenderTemplate);
              msg.Append(") already exists.\n");
              msg.Append("Aborting to avoid overwriting previous data.  Run job again in 1 minute or clear folder.");
              throw msg;
            
            outputDirectoryRenderTemplate = outputDirectoryRenderTemplate + "_";
            }
            **/
      }
      
      //MessageBox.Show(tmpFolderName);

      // start convert LOOP
      var newExtension = renderer.FileExtension.substring(1);

       // enumerate the files in the input directory
       var fileEnum = new Enumerator(Directory.GetFiles(inputDirectory));
      //MessageBox.Show("number of files in folder: ",fileEnum)
      var deleteCounterTest01 = 0;
       while (!fileEnum.atEnd()) {
         deleteCounterTest01 = deleteCounterTest01 + 1;
           var inputFile = fileEnum.item();
         //MessageBox.Show(Path.GetFileName(inputFile),"File Number: " + deleteCounterTest01);
           // Convert File
         var statusConvert = DoConvert(fileEnum, videoTrack, audioTrack, proj, newExtension, inputFileRegexp, outputDirectoryRenderTemplate, renderer, renderTemplate);
      
         fileEnum.moveNext();
         
       }
      
   counterDirectory++;
    selections.moveNext();
    }
   
}

function DoConvert(fileEnum, videoTrack, audioTrack, proj, newExtension, inputFileRegexp, outputDirectoryRenderTemplate, renderer, renderTemplate) {

      var inputFile = fileEnum.item();
      //MessageBox.Show(Path.GetFileName(inputFile),"Arquivo sendo testado");

        // skip files that don't end with the right extension
        if (null == inputFile.match(inputFileRegexp)) {
         //MessageBox.Show(Path.GetFileName(inputFile),"Media wrong extension");
            // continue;
        } else {


           // skip files that are not valid media files.
           var media = new Media(inputFile);
           if (!media.IsValid()) {
            //MessageBox.Show(Path.GetFileName(inputFile),"Media not video");
               // continue;

         } else {

              var videoStream = media.Streams.GetItemByMediaType(MediaType.Video, 0);
              var audioStream = media.Streams.GetItemByMediaType(MediaType.Audio, 0);

              // if needed, add a video event and associate video stream
              if (null != videoStream) {
                  var videoLength = videoStream.Length;
                  var videoEvent = new VideoEvent(new Timecode(), videoLength);
                  videoTrack.Events.Add(videoEvent);
                  var videoTake = new Take(videoStream);
                  videoEvent.Takes.Add(videoTake);
              }

              // if needed, add a audio event and associate audio stream
              if (null != audioStream) {
                  var audioLength = audioStream.Length;
                  var audioEvent = new AudioEvent(new Timecode(), audioLength);
                  audioTrack.Events.Add(audioEvent);
                  var audioTake = new Take(audioStream);
                  audioEvent.Takes.Add(audioTake);
              }

              var outputFileName = Path.GetFileNameWithoutExtension(inputFile) + newExtension;
              var outputPath = Path.Combine(outputDirectoryRenderTemplate, outputFileName);

              var status = DoRender(outputPath, renderer, renderTemplate);
              if (status == RenderStatus.Canceled) {
                  // may want have a dialog here allowing user to
                  // continue with remaining files.
                  // break;
               throw "Canceled by user ";
              } else if (status != RenderStatus.Complete) {
                  throw "Failed on input file: " + inputFile;
              }

              // clean up the project.
              videoTrack.Events.Clear();
              audioTrack.Events.Clear();
              proj.MediaPool.Remove(inputFile);
         }
      }
}

function DoRender(fileName, rndr, rndrTemplate) {
    FixFileName(fileName);

    // make sure the file does not already exist
    if (!overwriteExistingFiles && File.Exists(fileName)) {
        throw "File already exists: " + fileName;
    }

    // perform the render.  The Render method returns
    // a member of the RenderStatus enumeration.  If
    // it is anything other than OK, exit the loops.
    //var status = Vegas.Render(fileName, rndrTemplate);
    var status = Vegas.Render(fileName, rndrTemplate);
    return status;
}

function FixFileName(tmpFileName2Check)
{
   //MessageBox.Show("entrou FixFileName " + tmpFileName2Check);
    var replacementChar : System.Char = '-';
    var colon : System.Char = ':';
    tmpFileName2Check = tmpFileName2Check.Replace(Path.DirectorySeparatorChar, replacementChar);
   //MessageBox.Show("etapa 1 " + tmpFileName2Check);
    tmpFileName2Check = tmpFileName2Check.Replace(colon, replacementChar);
   //MessageBox.Show("etapa 2 " + tmpFileName2Check);
    var illegalCharCount = Path.GetInvalidPathChars;
    var i = 0;
    while (i < illegalCharCount) {
        tmpFileName2Check = tmpFileName2Check.Replace(Path.InvalidPathChars[i], replacementChar);
        i++;
    }
    return tmpFileName2Check;
}

function FixFolderName(outputDirectoryRenderTemplate : System.String) : System.String
{
   ////MessageBox.Show("entrou FixFileName " + outputDirectoryRenderTemplate);
    var replacementChar : System.Char = '-';
    var comma : System.Char = ',';
   var slash : System.Char = '/';
   var period : System.Char = '.';
    outputDirectoryRenderTemplate = outputDirectoryRenderTemplate.Replace(comma, replacementChar);
   ////MessageBox.Show("etapa 1 " + outputDirectoryRenderTemplate);
    outputDirectoryRenderTemplate = outputDirectoryRenderTemplate.Replace(slash, replacementChar);
   ////MessageBox.Show("etapa 2 " + outputDirectoryRenderTemplate);
   outputDirectoryRenderTemplate = outputDirectoryRenderTemplate.Replace(period, replacementChar);
   ////MessageBox.Show("etapa 3 " + outputDirectoryRenderTemplate);

    var illegalCharCount = Path.GetInvalidPathChars;
    var i = 0;
    while (i < illegalCharCount) {
        outputDirectoryRenderTemplate = outputDirectoryRenderTemplate.Replace(Path.InvalidPathChars[i], replacementChar);
        i++;
    }
    return outputDirectoryRenderTemplate;
}


class BatchRenderDialog extends Form {
    var browseButton : BrowseButton;
    var fileNameBox : TextBox;
    var templateTree : TemplateTreeView;
    var renderProject : RadioButton;
    var renderRegions : RadioButton;
    var renderSelection : RadioButton;

    function BatchRenderDialog() {
        this.Text = "Batch Render";
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.StartPosition = FormStartPosition.CenterScreen;
        this.Width = 600;

        var titleBarHeight = this.Height - this.ClientSize.Height;
        var buttonWidth = 80;

        fileNameBox = addTextControl("Base File Name", titleBarHeight + 6, 460, 10, defaultBasePath);

        browseButton = new BrowseButton(fileNameBox);
        browseButton.Left = fileNameBox.Right + 4;
        browseButton.Top = fileNameBox.Top - 2;
        browseButton.Width = buttonWidth;
        browseButton.Height = browseButton.Font.Height + 12;
        browseButton.Text = "Browse...";
        Controls.Add(browseButton);

        templateTree = new TemplateTreeView();
        templateTree.Left = 10;
        templateTree.Width = this.Width - 20;
        templateTree.Top = browseButton.Bottom + 10;
        templateTree.Height = 300;
        templateTree.CheckBoxes = true;
        Controls.Add(templateTree);
        FillTemplateTree();

        var buttonTop = templateTree.Bottom + 16;
        var buttonsLeft = this.Width - (2*(buttonWidth+10));

        renderProject = addRadioControl("Render Project", 6, buttonTop);
        renderSelection = addRadioControl("Render Selection", renderProject.Right, buttonTop);
        renderRegions = addRadioControl("Render Regions", renderSelection.Right, buttonTop);

        // New code added here to correctly identify whether to render selection, project, or region
        var dSelStart = Vegas.SelectionStart.ToMilliseconds();
        var dSelEnd = Vegas.SelectionStart.ToMilliseconds() + Vegas.SelectionLength.ToMilliseconds();
        var dCursor = Vegas.Cursor.ToMilliseconds();
       
        if (dSelStart == dCursor || dSelEnd == dCursor) {
            renderSelection.Checked = true;
        } else {
            renderProject.Checked = true;
        }
       
        var okButton = new Button();
        okButton.Text = "OK";
        okButton.Left = this.Width - (2*(buttonWidth+10));
        okButton.Top = buttonTop;
        okButton.Width = buttonWidth;
        okButton.Height = okButton.Font.Height + 12;
        okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
        AcceptButton = okButton;
        Controls.Add(okButton);

        var cancelButton = new Button();
        cancelButton.Text = "Cancel";
        cancelButton.Left = this.Width - (1*(buttonWidth+10));
        cancelButton.Top = buttonTop;
        cancelButton.Height = cancelButton.Font.Height + 12;
        cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        CancelButton = cancelButton;
        Controls.Add(cancelButton);

        this.Height = titleBarHeight + okButton.Bottom + 8;

    }

    function addTextControl(labelName, left, width, top, defaultValue) {
        var label = new Label();
        label.AutoSize = true;
        label.Text = labelName + ":";
        label.Left = left;
        label.Top = top + 4;
        Controls.Add(label);

        var textbox = new TextBox();
        textbox.Multiline = false;
        textbox.Left = label.Right;
        textbox.Top = top;
        textbox.Width = width - (label.Width);
        textbox.Text = defaultValue;
        Controls.Add(textbox);

        return textbox;
    }

    function addRadioControl(labelName, left, top) {
        var label = new Label();
        label.AutoSize = true;
        label.Text = labelName;
        label.Left = left;
        label.Top = top + 4;
        Controls.Add(label);

        var radiobutton = new RadioButton();
        radiobutton.Left = label.Right;
        radiobutton.Width = 36;
        radiobutton.Top = top;
        Controls.Add(radiobutton);

        return radiobutton;
    }

    function FillTemplateTree() {
        var renderers = new Enumerator(Vegas.Renderers);
        while (!renderers.atEnd()) {
            var renderer = renderers.item();
            var rendererNode = new TreeNode(renderer.FileTypeName);
            rendererNode.Tag = renderer;
            templateTree.Nodes.Add(rendererNode);
            var templates = new Enumerator(renderer.Templates);
            while (!templates.atEnd()) {
                var template = templates.item();
                var templateNode = new TreeNode(template.Name);
                var tag = new Object();
                tag.renderer = renderer;
                tag.template = template;
                templateNode.Tag = tag;
                rendererNode.Nodes.Add(templateNode);
                templates.moveNext();
            }
            renderers.moveNext();
        }
    }

    function GetCheckedTemplates() {
        var checkedTemplates = new ArrayList();
        var rendererNodes = new Enumerator(templateTree.Nodes);
        while (!rendererNodes.atEnd()) {
            var rendererNode = rendererNodes.item();
            GetCheckedTemplatesHelper(checkedTemplates, new Enumerator(rendererNode.Nodes));
            rendererNodes.moveNext();
        }
        return checkedTemplates;
    }

    function GetCheckedTemplatesHelper(checkedTemplates, templateNodes) {
        if (templateNodes.atEnd()) return;
        var templateNode = templateNodes.item();

        if (templateNode.Checked) {
            checkedTemplates.Add(templateNode.Tag);
        }
        templateNodes.moveNext();
        GetCheckedTemplatesHelper(checkedTemplates, templateNodes);
    }
}

// Button subclass that shows a save file dialog when clicked
class BrowseButton extends Button {
    var myResultBox = null;

    function BrowseButton(resultBox) {
        myResultBox = resultBox;
    }

    protected override function OnClick(e : EventArgs) {
        var saveFileDialog = new SaveFileDialog();
        saveFileDialog.Filter = "All Files (*.*)|*.*";
        saveFileDialog.CheckPathExists = true;
        saveFileDialog.AddExtension = false;
        if (null != myResultBox) {
            var filename = myResultBox.Text;
            var initialDir = Path.GetDirectoryName(filename);
            if (Directory.Exists(initialDir)) {
                saveFileDialog.InitialDirectory = initialDir;
            }
            saveFileDialog.DefaultExt = Path.GetExtension(filename);
            saveFileDialog.FileName = Path.GetFileNameWithoutExtension(filename);
        }
        if (System.Windows.Forms.DialogResult.OK == saveFileDialog.ShowDialog()) {
            if (null != myResultBox) {
                myResultBox.Text = Path.GetFullPath(saveFileDialog.FileName);
            }
        }
    }
}

class TemplateTreeView extends TreeView {

    protected function OnAfterCheck(e : TreeViewEventArgs) {
        super.OnAfterCheck(e);
        if (e.Node.Checked) {
            if (0 != e.Node.Nodes.Count) {
                if ((e.Action == TreeViewAction.ByKeyboard) || (e.Action == TreeViewAction.ByMouse)) {
                    SetChildrenChecked(new Enumerator(e.Node.Nodes), true);
                }
            } else if (!e.Node.Parent.Checked) {
                e.Node.Parent.Checked = true;
            }
        } else {
            if (0 != e.Node.Nodes.Count) {
                if ((e.Action == TreeViewAction.ByKeyboard) || (e.Action == TreeViewAction.ByMouse)) {
                    SetChildrenChecked(new Enumerator(e.Node.Nodes), false);
                }
            } else if (e.Node.Parent.Checked) {
                if (!AnyChildrenChecked(new Enumerator(e.Node.Parent.Nodes))) {
                    e.Node.Parent.Checked = false;
                }
            }
        }
    }

    protected function SetChildrenChecked(kidz, checked) {
        if (kidz.atEnd()) return;
        var kid = kidz.item();
        if (kid.Checked != checked)
            kid.Checked = checked;
        kidz.moveNext();
        SetChildrenChecked(kidz, checked);
    }

    protected function AnyChildrenChecked(kidz) : boolean {
        if (kidz.atEnd()) return false;
        var kid = kidz.item();
        if (kid.Checked)
            return true;
        kidz.moveNext();
        return AnyChildrenChecked(kidz);
    }
}
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    www.jetdv.com Forum Index -> Free Scripts All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB 2.0.11 © 2001, 2002 phpBB Group