//v0.1 - o4/2o15 //- initial //v0.3 - o5/2o15 //- new feature "ITEM", select item (supports full paths if the USEPATH switch is used, // which doesn't work with the native select) //- new feature "TOVAR", save current selection to memory (persistent storage) //- new feature "TOFILE", save current selection to file //- new feature "FROMVAR", load selection from memory //- new feature "NTH", select every n-th item //- new feature "RANDOM", select items randomly (formerly known as SelectRandom script command) //- new feature "LINEAR", select items linear (same as RANDOM, but not random o) //- new feature "AUTO", trigger for autoselection (simulate onafterfolderchange) //- new feature "SIMILARMETA", select files with similar meta data //- new feature "SIMILARMETAJS", select files with similar meta data using a jscript snippet //- new feature "FILTERDROP", un/select, un/hide items by choosing a filter from a dropdown //- new feature "FILTERLIST", un/select, un/hide items by choosing (multiple) filters from a list //- new switch "SKIPITEMSWITHPATH", skip items with paths when selecting from clip/file/mem //- new switch "SKIPITEMSWITHOUTPATH", skip items with no path when selecting from clip/file/mem //- new switch "USEPATH", select by full path instead of using only the names from clip/file/mem //- new option "PT" = pass through, to pass arguments through to the native select command //- new option "DESELECTNOMATCH", works like native DESELECTNOMATCH switch (deselects first) //- new option "NODESELECT", works like native @nodeselect modifier //- new option "APPEND", append selected items to files, memorized-variables, clipboard //- new option "GO", switches folder to the first item in clip/file/memory before selecting //- new option "MAKEVISIBLE", works like native MAKEVISIBLE switch (scroll into view), // but can also be used "standalone" to scroll to currently selected/checked items //- new option "EXACT", works like native EXACT switch (do not interpret pattern-chars) //- new option "XLOG", enable output and set level (defaults to normal if no value given) //Includes generic/enhanced variants of following addins: //- "SelectFromTxt (select files from text file)" (http://resource.dopus.com/viewtopic.php?f=35&t=23130) //- "Select every nth files in a lister" (http://resource.dopus.com/viewtopic.php?f=3&t=20185) //- "SelectRandom" (http://resource.dopus.com/viewtopic.php?f=35&t=23142) //- "Auto-select items when entering folders" (http://resource.dopus.com/viewtopic.php?f=35&t=24306) //- "Select by Filter buttons" (http://resource.dopus.com/viewtopic.php?f=35&t=22311) //- "Select Similar Dimensions" menu button" (http://resource.dopus.com/viewtopic.php?f=35&t=22428) //- "ScrollSelectionIntoView" (http://resource.dopus.com/viewtopic.php?f=35&t=22450) //v0.4 - o5/2o15 //- removed unused code, minor tweaks //- option SETTABVAR renamed to SETVAR //- option SETENVVAR renamed to SETENV //- new feature FROMVARDROP to easify picking of memorized selections //v0.4.1 - o5/2o15 //- no need for a selected item when using SIMILARMETAJS //v0.4.2 - o5/2o15 //- distance() function available for simple fuzzy selections //- new OPTION "JSBREAK" for custom rules on when to stop item selection/picking //- TOFILE and APPEND options now also work in conjunction with RANDOM/LINEAR //v0.4.3 - o6/2o15 //- MAKEVISIBLE fixed, threw error in previous upload //- JSBREAK finetuning: return true to stop item picking, false to skip item and null/undefined will select/pick //- JSFILTER performance gain //- Usage of Confighelper v1.2 and XLog 0.3 //v0.4.4 - o6/2o15 //- TOFILE/FROMFILE encoding-awareness added (did not always load selection-files correctly) //- new script config "AutoSelect.DeselectNoMatch" to deselect automatically selected first file //v0.4.5 - o6/2o15 //- the AUTO feature, to trigger auto-selection from commandline and not automatically by entering a folder, is now independent from the "AutoSelect" script configs (despite the list). //That means you can disable AutoSelect and still use it occasionally from a "SelectEx AUTO" button. AutoSelect.MakeVisible/DeselectNoMatch also don't apply anymore if invoked manually (use the regular switches for that). //v0.4.6 - o6/2o15 //- new switch "INDEST", select items in destination instead of source (SIMILARMETA/JS only) // This is similar to "Select SOURCETODEST=noext" but more powerful, as you can choose any metadata or item property to select similar items in the destination. // This command selects all items in dest, that match the first 8 characters from the name of any of the items selected in source. // I use this to select xmp or tiff-files and various jpg exports with different suffixes that belong to master files in the source (raw images). // SelectEx SIMILARMETAJS="return selItem.name.left(8)==item.name.left(8);" TODEST //v0.4.7 - o6/2o15 //- XLog updated to v0.4 //- temporary XLog initialisation information //v0.4.8 - o6/2o15 //- even more temporary XLog information //v0.4.9 - o6/2o15 //- missing output fixed for DO versions older than v11.13.1 //- XLog updated to v0.41 //- XLog initialisation and debug output removed //- "path not found" error handling improved //v0.5 - o7/2o15 //- new script config "AutoSelect.Actions" to customize on what type of folderchange the autoselection is done //- unified internal param-handling for RANDOM/LINEAR mode (was different because of merge with former "SelectRandom" command) //- FSMagic updated to v0.4 //- new features for the FOLDERS switch in combination with RECURSE and PATH. // - depthmin/depthmax to limit results to folders with a specific distance to the source folder // - subfldmin/subfldmax to limit results to folders with a specific number of subfolders // - skipsubfld to pre-filter/exclude all (sub)folders for which the subfldmin/max criteria already matched //v0.5.2 - 1o/2o15 //- fix for inaccessable folders //- new switch "NOFAIL" to prevent button scripts from aborting execution in specific situations (no items selected when trying to store selection e.g.) //- new option CLEARVAR to remove stored selections in variables (supports multiple variables, separated by ";") //- applying an empty selection container will give info message instead of error, but still fails the execution (override by NOFAIL if undesired) //v0.5.3 - o2/2o16 //- fix for FROMFILE creating nonexisting files //v0.5.3 - o5/2o16 //- fix for TOFILE not creating nonexisting files //todo //- ITEMCOUNT -> ITEMCOUNTMAX //- disable ITEMCOUNT when used with filesize options like MAXSIZETOTAL (in case its not done already) //- separator option for TOFILE etc.. //- re-test clearfiles() problem on data.func.command in top of SelectArrayItems() //issues //- SelectEx ITEM seams to toggle selection //- error message "Variable uses an Automation type not supported in JScript ..." // when using an /M type argument (desired for ITEM arg) /////////////////////////////////////////////////////////////////////////////// var template = //main features.. "FROMCLIP/S,FROMFILE/K,FROMVAR/O,FROMVARDROP/S,TOCLIP/S,TOFILE/K,TOVAR/O,CLEARVAR/K,ITEM/K,NTH/K,RANDOM/S,LINEAR/S,AUTO/S,SIMILARMETA/K,"+ "SIMILARMETAJS/K,FILTERDROP/O[,deselect,hide,hidenomatch],MAKEVISIBLE/O[checked],"+ //fromfile, fromclip, fromvar, fromvardrop "SKIPITEMSWITHPATH/S,SKIPITEMSWITHOUTPATH/S,EXACT/S,GO/S,GOPT/R,"+ //fromfile, fromclip, fromvar, item "USEPATH/S,"+ //tofile, tovar, toclip "APPEND/S,"+ //similarmetajs "INDEST/S,"+ //random, linear "PATH/K,RECURSE/S,SETVAR/K,SETENV/K,FOLDERS/O[subfldmin,subfldmax,skipsubfld,depthmin,depthmax],FILES/S,SINGLEFOLDER/S,SINGLEFOLDERMINCOUNT/K[<1>],"+ "ITEMCOUNTRND/S,ITEMCOUNT/K,ITEMCOUNTPERC/K,ACTION/K,NAME/K,MINSIZE/K,MAXSIZE/K,MAXSIZETOTAL/K,"+ "JSFILTER/K,JSBREAK/K,ECHO/S,COPYTOCOLL/K,COMMANDS/R,"+ //shared misc "DESELECTNOMATCH/S,NOFAIL/S,NODESELECT/S,XLOG/O[off,xit,error,warning,info,,trace,dump,all],PT/R"; //and MAKEVISIBLE /////////////////////////////////////////////////////////////////////////////// function OnInit(data){ //uid added via script wizard (do not change after publishing this script) var uid = "D6E6CF87-1FFB-4285-85F2-6C69727D2BD8"; //resource center url added via script wizard (required for updating) var url = "http://resource.dopus.com/viewtopic.php?f=35&t=24414"; data.name = "Command.Generic: SelectEx"; data.log_prefix = "SelectEx"; data.desc = "Extended Select command."; data.copyright = "tbone"; data.version = "0.5.3"; data.min_version = "11.5"; data.default_enable = true; var cmd = data.AddCommand(); cmd.name = "SelectEx"; cmd.method = "Command_SelectEx"; cmd.desc = data.desc; cmd.label = "SelectEx"; cmd.template = template; /////////////////////////////////////////////////////////////////////////// function ConfigHelper(data){ //v1.2 var t=this; t.d=data; t.c=data.config; t.cd=DOpus.Create.Map(); t.add=function(name, val, des){ t.l={n:name,ln:name. toLowerCase()}; return t.val(val).des(des);} t.des=function(des){ if (!des) return t; if (t.cd.empty) t.d.config_desc=t.cd; t.cd(t.l.n)=des; return t;} t.val=function(val){ var l=t.l; if (l.v!==l.x&&typeof l.v=="object") l.v.push_back(val);else l.v=t.c[l.n]=val;return t;} t.trn=function(){return t.des(t("script.config."+t.l.ln));}} /////////////////////////////////////////////////////////////////////////// var cfg = new ConfigHelper(data); cfg.add('XLog', DOpus.Create.Vector()). val(5).val("Off").val("Exception").val("Error").val("Warning").val("Info").val("Normal").val("Trace").val("Dump").val("All"). des('Console output level. The higher, the more output will be visible in the console window. '); cfg.add('AutoSelect', false). des('Enable automatic selection of items.'); cfg.add('AutoSelect.Actions', "normal,dblclk"). des('On what kind of folderchange to perform the automatic selection. You can use: normal, refresh, parent, root, back, forward, dblclk.'); cfg.add('AutoSelect.MakeVisible', true). des('Enable scrolling to automatically selected items.'); cfg.add('AutoSelect.DeselectNoMatch', true). des('Deselect items before automatic selection is applied (deselects automatically selected first file in folder if enabled e.g.).'); cfg.add('AutoSelect.List', DOpus.Create.Vector()). des('List of folder names and items to be selected automatically. '+ 'Paths and item names support regex if prefixed with "REGEX=", regular paths will be resolved (for aliases/env-vars).'). val(';you can use ; or // or # to comment out lines'). val(';syntax is: [REGEX=] => [REGEX=]'). val(''). val(';standard path (select program files)'). val('C:\\ => Program Files'). val(''). val(';alias for path and regex for item'). val('/home => REGEX=dopus.exe|dopusrt.exe'). val(''). val(';env-var in path and regex for item (all log files)'). val('%windir% => REGEX=.+\\.log$'). val(''). val(';using regex for the path'). val('REGEX=.*\\\\drivers\\\\etc => hosts'); } /////////////////////////////////////////////////////////////////////////////// var COMMAND_FAILURE = true; var COMMAND_USERABORT = true; var COMMAND_BADPARAMS = true; var COMMAND_SUCCESS = false; var fm = new FSMagic(); var gThis = this; /////////////////////////////////////////////////////////////////////////////// String.prototype.lTrim = function(chr){chr=chr||"\\s";return new String(this.replace(new RegExp("^"+chr+"*","i"),''));} String.prototype.rTrim = function(chr){chr=chr||"\\s";return new String(this.replace(new RegExp(chr+"*$","i"),''));} String.prototype.trim = function(chr){return this.lTrim(chr).rTrim(chr);} String.prototype.left = function(chrs){return this.substring(0,chrs);} String.prototype.right = function(chrs){return this.substring(this.length-chrs);} /////////////////////////////////////////////////////////////////////////////// function Command_SelectEx(data){ var args = ArgsMagic(data, null, template), result = null; //DumpObject(args); //return; if (args["XLOG"].exists){ XLog = args["XLOG"].value; } Log("CmdLine: " + data.cmdline,"D"); if (args["NODESELECT"].exists) data.func.command.deselect = false; if (args["NOFAIL"].exists) COMMAND_FAILURE = COMMAND_SUCCESS; if (0); else if (args["AUTO"].exists) return SelectEx_AUTO(data.func.command, data.func.sourcetab, args); else if (args["SIMILARMETA"].exists) return SelectEx_SIMILARMETA(data.func.command, data.func.sourcetab, data.func.desttab, args); else if (args["SIMILARMETAJS"].exists) return SelectEx_SIMILARMETAJS(data.func.command, data.func.sourcetab, data.func.desttab, args); else if (args["FILTERDROP"].exists) return SelectEx_FILTERMENU(data.func.dlg, data.func.command, data.func.sourcetab, args, "dropdown"); else if (args["FILTERLIST"].exists) return SelectEx_FILTERMENU(data.func.dlg, data.func.command, data.func.sourcetab, args, "multilist"); else if (args["FROMCLIP"].exists) return SelectEx_FROMCLIP(data.func.command, data.func.sourcetab, args); else if (args["FROMFILE"].exists) return SelectEx_FROMFILE(data.func.command, data.func.sourcetab, args); else if (args["FROMVAR"].exists) return SelectEx_FROMVAR(data.func.command, data.func.sourcetab, args); else if (args["CLEARVAR"].exists) return SelectEx_CLEARVAR(data.func.command, data.func.sourcetab, args); else if (args["FROMVARDROP"].exists) return SelectEx_FROMVARDROP(data.func.dlg, data.func.command, data.func.sourcetab, args); else if (args["ITEM"].exists) return SelectEx_ITEM(data.func.command, args, null); else if (args["NTH"].exists) return SelectEx_NTH(data.func.command, data.func.sourcetab, args); else if (args["RANDOM"].exists) return SelectEx_RNDLINEAR(data.func.command, data.func.sourcetab, args, true); else if (args["LINEAR"].exists) return SelectEx_RNDLINEAR(data.func.command, data.func.sourcetab, args, false); else if (args["TOCLIP"].exists) return SelectEx_TOCLIP(data.func.command, data.func.sourcetab, args); else if (args["TOFILE"].exists) return SelectEx_TOFILE(data.func.command, data.func.sourcetab, args); else if (args["TOVAR"].exists) return SelectEx_TOVAR(data.func.command, data.func.sourcetab, args); else if (args["MAKEVISIBLE"].exists) return SelectEx_MAKEVISIBLE(data.func.command, data.func.sourcetab, args, null); if (result===null){ Log("Bad/incomplete params.","X"); return COMMAND_BADPARAMS; } return result; } /////////////////////////////////////////////////////////////////////////////// function SelectEx_MAKEVISIBLE(cmd, sourcetab, args, item){ Log("SelectEx_MAKEVISIBLE():","T",1); /////////////////////////////////////////////////////////////////////////// function SwitchCheckboxMode( truefalse, cmd, sourcetab){ Log('SwitchCheckboxMode():',"T",1); var targetState = "off"; if (truefalse) targetState = "on"; cmd.RunCommand('Set CheckboxMode='+targetState); cmd.Clear(); sourcetab.Update(); var abort = 0; while ((truefalse != sourcetab.selstats.checkbox_mode) && (abort++ < 100)){ Log('Setting CheckboxMode failed to set:' + sourcetab.selstats.checkbox_mode + " target:"+targetState,"E"); DOpus.Delay(10); sourcetab.Update(); } if (abort){ Log('Setting CheckboxMode finally:' + sourcetab.selstats.checkbox_mode,"E"); Log('Took: '+ abort*10 +' milliseconds!',"E"); } Log("-","T",-1); return sourcetab.selstats.checkbox_mode; } cmd.ClearFiles(); cmd.deselect = false; sourcetab.Update(); //update tab for changed selection, fetch first selected item //and select it once more to make the MAKEVISIBLE switch work // for (var iEnum = new Enumerator(sourcetab.selected); !iEnum.atEnd();){ // var item = iEnum.item(); //iEnum.moveNext(); // DOpus.Output(" Running SelectEx MAKEVISIBLE.." + item.realpath); // cmd.RunCommand('SelectEx ITEM="'+item.realpath+'" EXACT MAKEVISIBLE'); // break; // } ///////////////////////// var wasCheckboxMode = (sourcetab.selstats.checkbox_mode==true); var isCheckboxMode = wasCheckboxMode; var numSelItems = sourcetab.stats.selitems; var numCheItems = sourcetab.stats.checkeditems; if (numCheItems+numSelItems==0){ Log("Aborting, nothing selected","D"); Log("-", "T",-1); return COMMAND_SUCCESS; } var prioCBSelection = args["MAKEVISIBLE"].options["checked"] || false; Log("PRIOCHECKED : " + prioCBSelection,"D"); Log("CHECKBOXMODE: " + isCheckboxMode,"D"); if (isCheckboxMode && numSelItems && (prioCBSelection==false || numCheItems==0)){ Log("Disabling checkbox mode to scroll for regular selection (has prio)","D"); isCheckboxMode = SwitchCheckboxMode( false, cmd, sourcetab); } Log("Scrolling selected items into view for "+(isCheckboxMode ? "CheckboxMode" : "RegularMode"),"D"); if (!item){ var selectedItems = new Enumerator(sourcetab.selected); var firstSelected = selectedItems.item(); item = new String(firstSelected.realpath); } //cmd.AddLine('Select "'+firstSelected.name+'" MAKEVISIBLE EXACT'); //cmd.Run(); Log("item : " + item,"D"); args["EXACT"] = {exists:true}; SelectEx_ITEM(cmd, args, new String(item)) if (wasCheckboxMode && !isCheckboxMode){ Log("Turning checkboxes back on","D"); isCheckboxMode = SwitchCheckboxMode( true, cmd, sourcetab); } Log("-","T",-1); return COMMAND_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// function SelectEx_RNDLINEAR(cmd, sourcetab, args, random){ Log("SelectEx_RNDLINEAR():","T",1); var fso = new ActiveXObject("Scripting.FilesystemObject"); /////////////////////////////////////////////////////////////////////////// function FriendlySizeToBytes(friendlySize){ var size = parseFloat(friendlySize=friendlySize.toLowerCase()); if (isNaN(size)) return null; if (friendlySize.match(/(\d|\s)(b|bytes?)$/)) ; else if (friendlySize.match(/(kb|kilobytes?)$/)) size*=1024; else if (friendlySize.match(/(mb|megabytes?)$/)) size*=1024*1024; else if (friendlySize.match(/(gb|gigabytes?)$/)) size*=1024*1024*1024; else if (friendlySize.match(/(tb|terabytes?)$/)) size*=1024*1024*1024*1024; else if (friendlySize.match(/(pb|petabytes?)$/)) size*=1024*1024*1024*1024*1024; else if (friendlySize.match(/(eb|exabytes?)$/)) size*=1024*1024*1024*1024*1024*1024; else size = null; return size; } /////////////////////////////////////////////////////////////////////////// function RegexToWildcardObj(arg){ if (arg.exists) return DOpus.FSUtil.NewWild(arg.value,"rf"); return null; } /////////////////////////////////////////////////////////////////////////// function ValidateSizeParameter(arg){ var value = arg.value; if (arg.exists && (value=FriendlySizeToBytes(arg.value))==null){ Log(arg.name+" malformed.", "X"); throw new Error(arg.name+" malformed."); } return value; } /////////////////////////////////////////////////////////////////////////// function GetFilteredItemCollections(sourcetab, args){ ////////////////////////////////////////////////////////////////////// function ReadFolder(path, recurse, level){ Log(" ["+path+"]..", "A"); level = level || 0; var iEnum = DOpus.FSUtil.ReadDir(path, false); if (iEnum.error!=0 && iEnum.error!=18 && iEnum.error!=2 ){ //18 = empty folder, 2=drive root Log("ReadDir ["+folderpath+"] failed, fEnum.error ["+iEnum.error+"]", "X"); throw new Error("ReadDir ["+folderpath+"] failed, fEnum.error ["+iEnum.error+"]"); } while (!iEnum.complete){ var item = iEnum.next(), itemSize = item.size.cy*10000; if ((args["MINSIZE"].exists || args["MAXSIZE"].exists || args["MAXSIZETOTAL"].exists) && item.is_dir && !item.got_size) itemSize = GetFolderSize(item.realpath); var result = AddItemWithFilter(item, itemSize, filteredItemCollections, args, level, SRFilter); if (item.is_dir && recurse) if (result !== FILTER_PASSED_SKIPSUBFOLDERS) ReadFolder(item.realpath, recurse, level+1); } } /////////////////////////////////////////////////////////////////////// function AddItemWithFilter(item, itemSize, filteredItemCollections, args, level, SRFilter){ var filRes = Filter(item, itemSize, args, level, SRFilter); switch(filRes){ case FILTER_PASSED: break; case FILTER_PASSED_SKIPSUBFOLDERS: break; case "jsfilter_exception": throw new Error("JSFilter failed, aborting."); default: return false; } filteredItemCollections.all.push_back(item); if (item.is_dir) filteredItemCollections.dirs.push_back(item); else filteredItemCollections.files.push_back(item); if (filRes == FILTER_PASSED_SKIPSUBFOLDERS) return filRes; return true; } /////////////////////////////////////////////////////////////////////// function Filter( item, itemSize, args, level, SRFilter){ if (item.is_dir && args["PATH"].exists){ var depthmin=null, depthmax=null; if (args["FOLDERS"].options["depthmin"] || args["FOLDERS"].options["depthmax"]){ if (args["FOLDERS"].options["depthmin"]) depthmin = args["FOLDERS"].options["depthmin"]*1; if (args["FOLDERS"].options["depthmax"]) depthmax = args["FOLDERS"].options["depthmax"]*1; if (depthmin!==null && (leveldepthmax)) return "depthmax"; //might never happen //Log("min: "+ args["FOLDERS"].options["depthmin"] +" max: " + args["FOLDERS"].options["depthmax"] + " lvl: " + level); } if (args["FOLDERS"].options["subfldmin"] || args["FOLDERS"].options["subfldmax"]){ var fld = fso.GetFolder(item.realpath); var minCount=null, maxCount=null; if (args["FOLDERS"].options["subfldmin"]) minCount = args["FOLDERS"].options["subfldmin"]*1; if (args["FOLDERS"].options["subfldmax"]) maxCount = args["FOLDERS"].options["subfldmax"]*1; if (minCount!==null && (minCount>fld.SubFolders.count)) return "subfldmin"; if (maxCount!==null && (maxCountdepthmax)) return FILTER_PASSED_SKIPSUBFOLDERS; } if (args["NAME"].exists && !args["NAME"].value.Match(item.name)) return "name"; if (args["MINSIZE"].exists && args["MINSIZE"].value > itemSize) return "minsize"; if (args["MAXSIZE"].exists && args["MAXSIZE"].value < itemSize) return "maxsize"; try{ if (SRFilter && SRFilter(item)!==false) return "jsfilter"; } catch (e){ return "jsfilter_exception"; } return FILTER_PASSED; } ////////////////////////////////////////////////////////////////////// var FILTER_PASSED=1; var FILTER_PASSED_SKIPSUBFOLDERS=3; var filteredItemCollections = { all : DOpus.Create.Vector(), files : DOpus.Create.Vector(), dirs : DOpus.Create.Vector()}; var SRFilter = null; if (args["JSFILTER"].exists){ try{ var SRFilter = new Function("item", args["JSFILTER"].value); } catch(e){ Log("Creating function from JSFilter failed: " + e,"X"); throw new Error("Creating function from JSFilter failed: " + e); } } if (args["PATH"].exists){ Log("Scanning and pre-filtering..", "D"); if (!DOpus.FSUtil.Exists(args["PATH"].value)){ Log("Path ["+args["PATH"].value+"] not found", "X"); throw new Error("Path ["+args["PATH"].value+"] not found"); } ReadFolder( args["PATH"].value, args["RECURSE"].exists); } else { Log("Sourcetab: " + sourcetab.path, "D"); for (var iEnum = new Enumerator(sourcetab.all); !iEnum.atEnd();){ var item = iEnum.item(), itemSize = item.size.cy*10000; iEnum.moveNext(); if ((args["MINSIZE"].exists || args["MAXSIZE"].exists || args["MAXSIZETOTAL"].exists) && item.is_dir && !item.got_size) itemSize = GetFolderSize(item.realpath); AddItemWithFilter(item, itemSize, filteredItemCollections, args, 0 /*level*/, SRFilter); } } return filteredItemCollections; } /////////////////////////////////////////////////////////////////////////// function SetResultVariables(sourcetab, args, value){ if (args["SETVAR"].exists) sourcetab.vars.Set(args["SETVAR"].value, value); if (args["SETENV"].exists){ var EM = new EnvMagic(); EM.Set(args["SETENV"].value, value); } } /////////////////////////////////////////////////////////////////////////// function PickItems(cmd, items, args){ var maxItems = args["ITEMCOUNT"].value; var maxSizeTotal = args["MAXSIZETOTAL"].value; var random = args["RANDOM"].exists; var jsBreak = null; Log("Picking items ("+items.count+" total)..","D"); /////////////////////////////////////////////////////////////////////// function MaxSizeReached(){ if (!args["MAXSIZETOTAL"].exists) return false; if (item.is_dir && !item.got_size) itemSize = GetFolderSize(item.realpath); if (((sizeTotal+itemSize)>args["MAXSIZETOTAL"].value)) return true; return false; } /////////////////////////////////////////////////////////////////////// cmd.ClearFiles(); if (args["JSBREAK"].exists){ try{ jsBreak = new Function("item", args["JSBREAK"].value); } catch(e){ Log("Creating function from JSBreak failed: " + e,"X"); throw new Error("Creating function from JSBreak failed: " + e); } } var sizeTotal = 0; if (random) { var randomsUsed = { "dummy":true }; var r = "dummy"; for (var i=0;i 0) itemsToSelect = items.count*(args["ITEMCOUNTPERC"].value/100); } if (itemsToSelect > items.count) itemsToSelect = items.count; if (args["ITEMCOUNTRND"].exists){ if (itemsToSelect > 1) itemsToSelect = Math.floor((Math.random()*itemsToSelect)+1); else itemsToSelect = Math.floor((Math.random()*items.count)+1); } return itemsToSelect; } /////////////////////////////////////////////////////////////////////////// function JoinItemsToString(collection, separator){ separator = separator || "\n"; var itemsSeparated = ""; for (var iEnum = new Enumerator(collection); !iEnum.atEnd();){ var item = iEnum.item(); iEnum.moveNext(); itemsSeparated += item.realpath + (!iEnum.atEnd()?separator:""); } return itemsSeparated; } /////////////////////////////////////////////////////////////////////////// function GetCollectionToPickFrom(filteredItemCollections, args){ if (args["SINGLEFOLDER"].exists && ((args["SINGLEFOLDERMINCOUNT"].value*1) <= filteredItemCollections.dirs.count)){ args["ITEMCOUNTRND"].exists = false; args["ITEMCOUNT"].value = 1; args["ITEMCOUNTPERC"].exists = false; return filteredItemCollections.dirs; } if (args["FOLDERS"].exists && !args["FILES"].exists) return filteredItemCollections.dirs; if (args["FILES"].exists && !args["FOLDERS"].exists) return filteredItemCollections.files; return filteredItemCollections.all; } /////////////////////////////////////////////////////////////////////////// function SelectItemsInFiledisplay(args, cmd){ if (!args["PATH"].exists){ Log("Selecting items..","D"); cmd.RunCommand("Select FROMSCRIPT EXACT"+ (args["DESELECTNOMATCH"].exists?" DESELECTNOMATCH":"")+ (args["MAKEVISIBLE"].exists?" MAKEVISIBLE":"") ); return true; } return false; } /////////////////////////////////////////////////////////////////////////// function SetResults(sourcetab, cmd, args){ var content = null; if (args["SETVAR"].exists || args["SETENV"].exists || args["TOFILE"].exists) content = JoinItemsToString(cmd.files, "\n"); if (args["SETVAR"].exists || args["SETENV"].exists) SetResultVariables(sourcetab, args, content); if (args["TOFILE"].exists){ var fm = new FSMagic(); var file = fm.OpenFile(args["TOFILE"].value, args["APPEND"].exists?"a":"w"); if (file!==null){ file.WriteLine(content); file.Close(); } } return (content!==null); } /////////////////////////////////////////////////////////////////////////// function TriggerFileTypeActions(args, cmd){ if (args["ACTION"].exists){ Log("Triggering action ["+args["ACTION"].value+"]..","D"); cmd.RunCommand("FileType ACTION="+args["ACTION"].value); return true; } return false; } /////////////////////////////////////////////////////////////////////////// function ExecuteCommands(args, cmd){ if (args["COMMANDS"].exists && cmd.files.count){ Log("Running commands..","D"); var commands = args["COMMANDS"].value.split("\\n"); for(var c=0;c":""); for (var iEnum = new Enumerator(cmd.files); !iEnum.atEnd();){ var item = iEnum.item(); iEnum.moveNext(); items += item.realpath; if (!iEnum.atEnd()) items += "
"; } Log(items); return true; } return false; } /////////////////////////////////////////////////////////////////////////// function CopyToCollection(args, cmd){ if (args["COPYTOCOLL"].exists){ var colName = args["COPYTOCOLL"].value; Log("Copying to collection ["+colName+"]..","D"); var cmdCol = DOpus.Create.Command(); cmdCol.AddLine('CreateFolder "coll://'+colName+'"'); cmdCol.AddLine('Copy COPYTOCOLL=member TO "coll://'+colName+'"'); var addedItems = false; for (var iEnum = new Enumerator(cmd.files); !iEnum.atEnd();){ var item = iEnum.item(); iEnum.moveNext(); if (!DOpus.FSUtil.Exists("coll://"+colName+"/"+item.name)){ cmdCol.AddFile(item); addedItems = true; } } //as selected files in source will be used instead (bug?) //issue: http://resource.dopus.com/viewtopic.php?f=3&t=24406 if (addedItems) cmdCol.Run(); return true; } return false; } /////////////////////////////////////////////////////////////////////////// function GetFolderSize(path){ var size = fso.GetFolder(path).Size; if (!isNaN(parseInt(size,10))) return size; return null; } /////////////////////////////////////////////////////////////////////////// if (!args["ITEMCOUNT"].exists) args["ITEMCOUNT"].value = 1; args["NAME"].value = RegexToWildcardObj(args["NAME"]); args["MINSIZE"].value = ValidateSizeParameter(args["MINSIZE"]); args["MAXSIZE"].value = ValidateSizeParameter(args["MAXSIZE"]); args["MAXSIZETOTAL"].value = ValidateSizeParameter(args["MAXSIZETOTAL"]); DumpArgs(args); var filteredItemCollections = GetFilteredItemCollections(sourcetab, args); var filteredItemCollection = GetCollectionToPickFrom(filteredItemCollections, args); if (filteredItemCollection.count==0){ SetResultVariables(sourcetab, args, ""); Log("No items, aborting","I"); return COMMAND_FAILURE; } args["ITEMCOUNT"].value = GetNumberOfItemsToSelect(args, filteredItemCollection); var pickedItemsCommand = PickItems(cmd, filteredItemCollection, args); //params.itemCount, params.maxSizeTotal, params.jsBreak, random); var voidItemsCopied = CopyToCollection(args, pickedItemsCommand); //if copytocoll given var voidItemsReturned = SetResults(sourcetab, pickedItemsCommand, args); //if variable names given var voidItemsSelected = SelectItemsInFiledisplay(args, pickedItemsCommand); //if no path given var voidActionsTriggered = TriggerFileTypeActions(args, pickedItemsCommand); //if action given var voidCommandsExecuted = ExecuteCommands(args, pickedItemsCommand); //if commands given var voidItemsEchoed = EchoItemsToConsole(args, pickedItemsCommand); //if echo enabled Log("Done.","D"); Log("-","T",-1); return COMMAND_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// function EnvMagic(scope){ //v0.1 this.scope = scope || "Process"; try{this.shell=shell} catch(e){this.shell=new ActiveXObject("WScript.Shell")}; this.env = this.shell.Environment(this.scope); /////////////////////////////////////////////////////////////////////////// this.Set = function (varname, value, scope){ var env = scope?this.shell.Environment(scope):this.env; env(varname) = value; return value; } /////////////////////////////////////////////////////////////////////////// this.Get = function (varname, scope){ var env = scope?this.shell.Environment(scope):this.env; return env(varname); } /////////////////////////////////////////////////////////////////////////// this.Remove = function (varname, scope){ var env = scope?this.shell.Environment(scope):this.env; return env.Remove(varname); } /////////////////////////////////////////////////////////////////////////// this.Expand = function (varString){ return this.shell.ExpandEnvironmentStrings(varString); } } /////////////////////////////////////////////////////////////////////////////// function PrintParams( params){ var maxLen = 0; for(param in params) if (param.length > maxLen) maxLen = param.length; for(param in params){ var pad = ""; while (pad.length+param.length maxLen) maxLen = arg.length; for(arg in args){ if (!isNaN(parseInt(arg,10))) continue; //skip numbered index var pad = ""; while (pad.length+arg.length"); if (parts.length!=2) continue; Log("Entry: " + list(i),"D"); var path = parts[0].trim(); if (path.substring(0,6)=="REGEX="){ path = path.substring(6); } else { path = path!=""?new String(DOpus.FSUtil.Resolve(path)):path; path = path.replace(/\\/g,'\\\\')+"$"; } Log(" Path: " + path,"D"); Log(" TabPath: " + tabPath,"D"); if (!tabPath.match(new RegExp(path,"i"))){ Log(" No path match","D"); continue; } var item = parts[1].trim(); selItems[selItems.length] = item; } if (selItems.length){ Log("SelItems: " + selItems,"D"); args["USEPATH"] = {exists:true}; SelectArrayItems(cmd, sourcetab, args, selItems); } Log("-","T",-1); return; } /////////////////////////////////////////////////////////////////////////////// function SelectEx_FILTERMENU(dlg, cmd, sourcetab, args, type){ Log("SelectEx_FILTERMENU():","T",1); /////////////////////////////////////////////////////////////////////////// function GetFilterNamesVector(){ var filtersPath = DOpus.FSUtil.Resolve("/dopusdata\\filters"); var fEnum = DOpus.FSUtil.ReadDir(filtersPath); if (fEnum.error!=0 && fEnum.error!=18 && fEnum.error!=2 ) //18 = empty folder, 2=drive root throw new Error(0,"ReadDir ["+filtersPath+"] failed, fEnum.error ["+fEnum.error+"]"); var list = DOpus.Create.Vector(); while (!fEnum.complete){ var filterItem = fEnum.next(); if (filterItem.is_dir == true) continue; if (filterItem.ext.toLowerCase() != ".ofi") continue; list.push_back(filterItem.name_stem); } return list; } /////////////////////////////////////////////////////////////////////////// function OpenMenu(dlg, type, filters, filterFlags){ dlg.title = "Select Filters"; dlg.message = "Check filters to "+filterFlags.replace(",",", ")+" items:" dlg.buttons = "Ok|Cancel"; dlg.choices = filters; if (type=="dropdown") dlg.menu = 0; if (type=="multilist") dlg.list = 0; dlg.Show(); return dlg.result; } /////////////////////////////////////////////////////////////////////////// function AddSelection(cmd, filterName, filterFlags){ var cmdLine = 'Select "'+filterName+'" FILTER FILTERFLAGS="'+filterFlags+'"'+ (args["MAKEVISIBLE"].exists?' MAKEVISIBLE':'')+ (args["PT"].exists?' '+args["PT"].value:'') ; cmd.AddLine(cmdLine); Log("Command: " + cmdLine,"D"); } /////////////////////////////////////////////////////////////////////////// Log("DESELECTNOMATCH: " + args["DESELECTNOMATCH"].exists,"D"); Log("MAKEVISIBLE : " + args["MAKEVISIBLE"].exists,"D"); Log("PT : " + args["PT"].value,"D"); cmd.deselect = false; if (args["DESELECTNOMATCH"].exists){ Log("cmd.AddLine(Select NONE);","D"); cmd.AddLine('Select NONE'); } if (type=="dropdown") var filterFlags = args["FILTERDROP"].value; if (type=="multilist") var filterFlags = args["FILTERLIST"].value; var filters = GetFilterNamesVector(); if (!filters.count){ Log("No filters found.","X"); Log("-","T",-1); return COMMAND_FAILURE; } var result = OpenMenu(dlg, type, filters, filterFlags); if (result==0){ Log("User abort.","T",-1); return COMMAND_USERABORT; } if (type=="multilist") for(var c=0;c str2.length) { return 1 - distance / str1.length; } else { return 1 - distance / str2.length; } } /////////////////////////////////////////////////////////////////////////// //work in progess function dis(selStr, str) { selStr = selStr.toLowerCase().replace(/[#0123456789\.\-\(\)]/g,""); str = str.toLowerCase().replace(/[#0123456789\.\-\(\)]/g,""); selStr = selStr.toLowerCase().replace(/^|\sthe\s|$/g,""); str = str.toLowerCase().replace(/^|\sthe\s|$/g,""); //DOpus.Output(str); return false; var selItemWords = new String(selStr).split(" "), selItemWords2 = []; var itemWords = new String(str).split(" "), itemWords2 = []; for(var i=0;i 0.9) { match = true; break; } } if (match) matches++; //DOpus.Output("itemWords2[i]="+itemWords2[i]); //DOpus.Output(" selStr="+selStr); } var perc = (matches*100)/itemWords.length; //var perc = (itemWords.length*100)/matches; //DOpus.Output(selStr + " " + perc.toFixed(2)); if (perc>15){ return true; } return false; //if (matches != itemWords.length) return 0; return matches; } /////////////////////////////////////////////////////////////////////////////// function SelectEx_SIMILAR(cmd, sourcetab, desttab, args, metas, jsCompare){ Log("SelectEx_SIMILAR():","T",1); /////////////////////////////////////////////////////////////////////////// var selFilesEnum = new Enumerator(sourcetab.selected_files), selItem = null; if (!selFilesEnum.atEnd()) selItem = selFilesEnum.item(); if (!selItem){ Log("No item selected or passed.","W"); //Log("-","T",-1); //return COMMAND_FAILURE; } if (metas){ var selItemMetas = [] for (var i=0;i"); if (parts.length>1) opValue = parts.slice(1).join(""); this.options[opName] = opValue; } if (!(!this.value && subOpsTemplate)) return; if (!(match = subOpsTemplate.match(/\<(.+?)\>/))) return; this.options[match[1]] = true; this.value = match[1]; } /////////////////////////////////////////////////////////////////////////// var types = {s:"switch",k:"keyword",o:"optional",n:"numeric",m:"multiple",r:"raw"}; var names = template.replace(/\/(.)\,/g,"/$1;").replace(/\]\,/g,"];").split(";"), args = []; for(arg in names) { var parts = names[arg].split("/"); var name=parts[0].toUpperCase(), subOpsTemplate=null; var parts2 = parts[1].split("["); var type=parts2[0].toLowerCase(); if (parts2.length>1) subOpsTemplate = parts2[1].substring(0,parts2[1].length-1); var exists=(data&&data.func.args.got_arg[name])||(jsonData&&(jsonData[name]!=undefined))||false; var value = (data && data.func.args[name]) || (jsonData && jsonData[name]) || undefined; args.push( args[name] = new Arg(name, types[type], exists, value, subOpsTemplate )); } /////////////////////////////////////////////////////////////////////////// args.Get = function( argName, configName, noneValue){ var arg = this[argName = argName.toUpperCase()]; if (!arg) throw new Error(0, "Unknown parameter ["+argName+"]"); if (arg.exists) return arg.value; //DOpus.Output("argName: " + argName); //DOpus.Output("configName: " + configName); if (!configName) return noneValue; if (typeof Script.config[configName] == "string") return new String(""+Script.config[configName]); return Script.config[configName]; } return args; } /////////////////////////////////////////////////////////////////////////////// function DumpObject(o, name, upperCaseProps, self, level){ this.version = 0.4; name = name || "unnamed"; if (self == undefined) DOpus.Output("DumpObject(): ["+name+"]"); var maxLen = 0; upperCaseProps = upperCaseProps || false; self = self || false; level = level || " "; for(prop in o) if (prop.length > maxLen) maxLen = prop.length; for(prop in o) { var pad = ""; while (pad.length+prop.length