-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_folders.py
More file actions
executable file
·1853 lines (1619 loc) · 72.6 KB
/
Copy path_folders.py
File metadata and controls
executable file
·1853 lines (1619 loc) · 72.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
__version__ = "$Rev: 529 $ on $Date: 2014-01-09 13:51:39 +0100 (do, 09 jan 2014) $ by $Author: quintijn $"
# This file is part of a SourceForge project called "unimacro" see
# http://unimacro.SourceForge.net and http://qh.antenna.nl/unimacro
# (c) copyright 2003 see http://qh.antenna.nl/unimacro/aboutunimacro.html
# or the file COPYRIGHT.txt in the natlink\natlink directory
#
# grammar: _folders.py
# Written by: Quintijn Hoogenboom (QH softwaretraining & advies)
# starting 2003, revised QH march 2011
#
"""with this grammar, you can reach folders, files and websites from any window.
From some windows (myu computer and most dialog windows) the folders and files
can be called directly by name if they are in the foreground.
If you are in a child window (often a file dialog window) the specified
folder is put into the filename text box, if you are in the Windows
Explorer or in the Internet Explorer file or drive is put in the
address text box, and otherwise a new window is opened with the
specified folder.
This grammar now makes use of ini files, to show and edit the contents
of the lists used.
Several "meta actions" are used, eg <<filenameenter>> and <<filename
exit>> when entering were exiting the file name text box in a file
dialog. These actions can be tailored for specific programs, like
some office programmes to behave different, or for WinZip. See examples
in actions.ini (call with "Edit Actions"/"Bewerk acties")
In the inifile also the commands for start this computer or start
windows explorer must be given. Correct these commands ("Edit
Folders"/"Bewerk folders") if they do not work correct.
New feature: if you want to use xxexplorer (can be used hands-free very
easy, look in http://www.netez.com/xxExplorer), in section [general]
you can put a variable
xxexplorer = path to exe or false ('')
This explorer is then taken if you are in or if Explorer is explicitly asked for.
The strategy for "New" and "Explorer" (when you say "new", "nieuw",
"explorer" in the folder command, are complicated, look below
The site part is only used if you enter a valid folder in siteRoot below.
With this command you can quickly enter a complicated set of there we go agains.
The subversion additional commands are only valid if you specify a valid subversion
client in the ini file general section.
"""
import string, types, re, copy
import natlink
import os, sys, time, fnmatch
import win32gui, win32con
from win32com.client import Dispatch
import inivars # for IniError
import messagefunctions as mess
#, win32com
import natlinkcorefunctions # getExtendedEnv
from actions import doAction as action
from actions import doKeystroke as keystroke
from utilsqh import *
from actions import do_YESNO as YesNo
import webbrowser
natut = __import__('natlinkutils')
natqh = __import__('natlinkutilsqh')
natbj = __import__('natlinkutilsbj')
# for substituting environment variable like %HOME% in a file path:
# and %DESKTOP% in a file path.
# %HOME% defaults to your my documents folder, but can be in the system environment variables.
reEnv = re.compile('%([A-Z_]+)%')
reOnlyLowerCase = re.compile(r'^[a-z]+$')
reLettersSpace = re.compile(r'^[a-zA-Z ]+$')
###########################################################
# classes for this computer and windows explorer:
Classes = ('ExploreWClass', 'CabinetWClass')
# extra for sites (QH)
siteRoot = 'D:\\projects\\sitegen'
if siteRoot and not os.path.isdir(siteRoot) :
## print "grammar _folder: site commands skipped"
siteRoot = ""
else:
if not siteRoot in sys.path:
#print 'append to sys.path: %s'% siteRoot
sys.path.append(siteRoot)
# some child windows have to behave as top window (specified in ini file):
# note: title is converted to lowercase, only full title is recognised
ancestor = natbj.IniGrammar
class ThisGrammar(ancestor):
"""grammar for quickly going to folders, files and websites
"""
language = natqh.getLanguage()
name = "folders"
iniIgnoreGrammarLists = ['subfolders', 'subfiles'] # on the fly in CabinetWClass
# commands with special status, must correspond to a right hand side
# of a ini file entry (section foldercommands or filecommands)
# remote, subversion, openwith have hardcoded details.
optionalfoldercommands = ['new', 'explorer', 'paste', 'copy', 'remote', 'subversion']
optionalfilecommands = ['copy', 'paste', 'edit', 'paste', 'remote', 'subversion', 'openwith']
# only used if siteRoot is a valid folder:
optionalsitecommands = ['input', 'output', 'local', 'online']
gramSpec = """
<folder> exported = folder ({folders}|{subfolders}|{folders}<foldercommands>|{subfolders}<foldercommands>);
<disc> exported = drive ({letters} | {letters} <foldercommands>); # add + later again
<thisfolder> exported = this folder <foldercommands>;
<foldercommands> = {foldercommands}| on {letters} |
(subversion) {subversionfoldercommands};
<folderup> exported = folder up|folder up {n1-10};
<file> exported = file ({files}|{subfiles}|{files}<filecommands>|{subfiles}<filecommands>); # add dot {extensions} later again
<thisfile> exported = this file <filecommands>;
<filecommands> = {filecommands}| (on {letters}) |
('open with') {fileopenprograms}|
(subversion) {subversionfilecommands};
<website> exported = website ({websites} | {websites} <websitecommands>);
<thiswebsite> exported = (this website) <websitecommands>;
<websitecommands> = ('open with') {websiteopenprograms};
## set all environment variables into the folders list...
<setenvironmentfolders> exported = set environment folders;
"""
# specific part in use by Quintijn:
if siteRoot:
gramSpec = gramSpec + """
<site> exported = site ({sites}|{sites} <sitecommands>);
<siteshort> exported = site <sitecommands>;
<sitecommands> = {sitecommands} | {sitecommands} (<foldercommands>|<websitecommands>) |
<foldercommands> | <websitecommands>;
"""
def initialize(self):
if not self.language:
print "no valid language in grammar "+__name__+" grammar not initialized"
return
self.load(self.gramSpec)
self.lastSite = None
self.switchOnOrOff() # initialises lists from inifile, and switches on
# if all goes well (and variable onOrOff == 1)
self.envDict = natlinkcorefunctions.getAllFolderEnvironmentVariables() # for (generalised) environment variables
self.subfiles = self.subfiles = self.activeFolder = None # for catching on the fly in explorer windows (CabinetClassW)
self.className = None
def gotBegin(self,moduleInfo):
if self.checkForChanges:
self.checkInifile() # refills grammar lists and instance variables
# if something changed.
if self.mayBeSwitchedOn == 'exclusive':
print "exclusive (_folders), do switchOnOrOff"
self.switchOnOrOff()
hndle = moduleInfo[2]
if hndle and (self.trackAutoFiles or self.trackAutoFolders):
className = win32gui.GetClassName(hndle)
activefolder = self.getActiveFolder(hndle, className)
#print 'activefolder: %s'% activefolder
if activefolder and os.path.isdir(activefolder) and activefolder != self.activeFolder:
self.fillListsForActiveFolder(activefolder, className)
print 'set %s (sub)files and %s subfolders'% (len(self.subfilesDict), len(self.subfoldersDict))
else:
if self.activeFolder:
self.emptyListsForActiveFolder()
elif self.activeFolder:
self.emptyListsForActiveFolder()
def gotResultsInit(self,words,fullResults):
if self.mayBeSwitchedOn == 'exclusive':
print 'recog folders, switch off mic'
natbj.SetMic('off')
self.wantedFolder = self.wantedFile = self.wantedWebsite = None
def fillList(self, listName):
"""fill a list in the grammar from the data of the inifile
overload, because the list sites is special:reversed
the section [site] must exist,on the right side is to spoken form.
"""
#print 'fill list', listName
if listName == 'sites':
if not siteRoot:
print 'sites rules ignored'
self.emptyList(listName)
return # skip the site part
self.sitesDict = self.getListOfSites(siteRoot)
items = self.sitesDict.keys()
self.setList(listName, items)
self.ini.writeIfChanged()
self.sitesInstances = {} # to be filled with instance of a site
return items
elif listName == 'folders':
if self.foldersDict:
items = self.foldersDict.keys()
self.setList('folders', items)
return items
else:
print 'no folders to set list to'
self.emptyList('folders')
elif listName == 'files':
if self.filesDict:
items = self.filesDict.keys()
self.setList('files', items)
return items
else:
print 'no files to set list to, edit _folders.ini if you wish to call individual files...'
self.emptyList('files')
elif listName in ['subversionfilecommands', 'subversionfoldercommands']:
if self.doSubversion:
return ancestor.fillList(self, listName)
else:
self.emptyList(listName)
else:
return ancestor.fillList(self, listName)
def fillInstanceVariables(self):
"""fills the necessary instance variables
take the lists of folders, virtualdrives (optional) and remotedrives (optional).
"""
self.xxExplorer = self.ini.get('general', '2xexplorer')
# extract special variables from ini file:
self.virtualDriveList = self.ini.get('virtualdrives')
#checking the paths of virtualDriveList:
for dr in self.virtualDriveList[:]:
folder1 = self.ini.get('virtualdrives', dr)
folder = self.substituteFolder(folder1)
if not os.path.isdir(folder):
print 'warning _folders, virtualdrive "%s" does not exist: %s'% (dr, folder)
self.virtualDriveList.remove(dr)
self.ini.delete('virtualdrives', dr)
self.ini.set('obsolete virtualdrives', dr, folder1)
# checking the passes of all folders:
foldersList = self.ini.get('folders')
self.foldersDict = {}
for f in foldersList:
folder = self.substituteFolder(self.ini.get('folders', f))
if not os.path.isdir(folder):
print 'warning _folders, folder "%s" does not exist (move away): "%s"'% (f, folder)
self.ini.delete('folders', f)
self.ini.set('obsolete folders', f, folder)
continue
self.foldersDict[f] = folder
# track virtual drives if in ini file:
self.trackFolders = self.ini.getList('general', 'track folders virtualdrives')
self.trackFiles = self.ini.getList('general', 'track files virtualdrives')
# in order to accept .py but it should be (for fnmatch) *.py etc.:
self.acceptFileExtensions = self.ini.getList('general', 'track file extensions')
self.ignoreFilePatterns = self.ini.getList('general', 'ignore file patterns')
# these are for automatic tracking the current folder:
self.trackAutoFolders = self.ini.getBool('general', 'automatic track folders')
self.trackAutoFiles = self.ini.getBool('general', 'automatic track files')
windowsVersion = natqh.getWindowsVersion()
if (self.trackAutoFiles or self.trackAutoFolders) and windowsVersion in ('XP', '2000', 'NT4', 'NT351', '98'):
print '_folders: the options for "automatic track files" and "automatic track folders" of a directory probably do not work for this Windows version: %s'% windowsVersion
self.doSubversion = self.ini.get('general', 'subversion executable')
if self.doSubversion:
if not os.path.isfile(self.doSubversion):
print 'not a valid path to subversion executable: %s, ignore'% self.doSubversion
self.doSubversion = None
self.foldersSections = ['folders']
# track folders:
for trf in self.trackFolders:
if not trf:
continue
trf2 = self.substituteFolder(trf)
if not os.path.isdir(trf2):
print 'warning, no valid folder associated with: %s (%s) (skip for track virtualdrives)'% (trf, trf2)
continue
subf = [f for f in os.listdir(trf2) if os.path.isdir(os.path.join(trf2, f))]
self.trackFoldersSection = 'folders %s'% trf
self.foldersSections.append(self.trackFoldersSection)
self.acceptVirtualDrivesFolder(trf, trf2) # without f, take virtualdrive itself...
for f in subf:
self.acceptVirtualDrivesFolder(trf, trf2, f)
self.cleanupIniFoldersSection(self.trackFoldersSection, trf)
self.removeObsoleteIniSections(prefix="folders ", validPostfixes=self.trackFolders)
# do the files:
self.filesDict = {}
self.trackFiles = self.ini.getList('general', 'track files virtualdrives')
# in order to accept .py but it should be (for fnmatch) *.py etc.:
self.acceptFileExtensions = self.ini.getList('general', 'track file extensions')
self.ignoreFilePatterns = self.ini.getList('general', 'ignore file patterns')
self.filesSections = ['files']
# from section files (manual):
filesList = self.ini.get('files')
for f in filesList[:]:
filename = self.substituteFilename(self.ini.get('files', f))
if not os.path.isfile(filename):
print 'warning _folders, file "%s" does not exist: "%s"'% (f, filename)
self.ini.delete('files', f)
self.ini.set('obsolete files', f, filename)
continue
self.filesDict[f] = filename
for trf in self.trackFiles:
if not trf:
continue
trf2 = self.substituteFolder(trf)
if not os.path.isdir(trf2):
print 'warning, no valid folder associated with: %s (%s) (skip for track files)'% (trf, trf2)
continue
filesList = [f for f in os.listdir(trf2) if os.path.isfile(os.path.join(trf2, f))]
self.trackFilesSection = 'files %s'% trf
self.filesSections.append(self.trackFilesSection)
for f in filesList:
self.acceptFileInFilesDict(trf, trf2, f)
self.cleanupIniFilesSection(self.trackFilesSection, trf)
self.removeObsoleteIniSections(prefix="files ", validPostfixes=self.trackFiles)
self.childBehaveLikeTop = self.ini.getDict('general', 'child behaves like top')
# save changes if there were any:
self.ini.writeIfChanged()
def acceptVirtualDrivesFolder(self, vd, realfolder, foldername=None):
"""check validity of virtualdrive subfolder and put or remove from inifile
add to foldersDict if applicable
"""
if foldername is None:
#print 'virtual drive: %s, %s'% (vd, realfolder)
f = vd
else:
f = foldername
if not reLettersSpace.match(f): # take only readable/speakable, only those are accepted by inivars
#print 'skipping: %s'% f
return # nothing to do
section = self.trackFoldersSection
spoken = self.ini.getList(section, f, ['xpqzyx'])
spoken = filter(None, spoken)
if spoken == ['xpqzyx'] or not spoken:
if foldername:
spoken = [f]
else:
spoken = [vd, os.path.split(realfolder)[-1]]
if spoken[0] == spoken[1]:
spoken = spoken[:1]
#print 'spoken for virtual drive: %s'% spoken
self.ini.set(section, f, spoken)
#else:
if not spoken:
return
for sp in spoken:
if foldername:
self.foldersDict[sp] = vd + ':/' + foldername
else:
self.foldersDict[sp] = vd
def getActiveFolder(self, hndle=None, className=None):
"""get active folder (only explorer and dialog #32770)
"""
if hndle is None:
hndle = natlink.getCurrentModule()[2]
if not hndle:
return
if className is None:
className = win32gui.GetClassName(hndle)
if className == "CabinetWClass":
return mess.getFolderFromCabinetWClass(hndle)
elif className == '#32770':
return mess.getFolderFromDialog(hndle, className)
def fillListsForActiveFolder(self, activefolder, className):
"""fill list of files and subfolders
also set activefolder and className
this is for the automatic filling of the active window (either explorer, CabinetWClass,
or child #32770.
Seems to fail in windows XP and before.
"""
subs = os.listdir(activefolder)
subfolders = [s for s in subs if os.path.isdir(os.path.join(activefolder, s))]
subfiles = [s for s in subs if os.path.isfile(os.path.join(activefolder, s))]
self.subfoldersDict = self.getSpokenFormsDict(subfolders)
self.subfilesDict = self.getSpokenFormsDict(subfiles, extensions=1)
if self.trackAutoFiles:
self.setList('subfiles', self.subfilesDict.keys())
if self.trackAutoFolders:
self.setList('subfolders', self.subfoldersDict.keys())
self.activeFolder = activefolder
self.className = className
def emptyListsForActiveFolder(self):
"""no sublists, empty
"""
if self.trackAutoFiles:
self.emptyList('subfiles')
self.subfilesDict.clear()
if self.trackAutoFolders:
self.emptyList('subfolders')
self.subfoldersDict.clear()
self.className = None
self.activeFolder = None
def cleanupIniFoldersSection(self, section, vd):
"""cleanup the current ini folder ... section (for non existing folders)
"""
section = self.trackFoldersSection
for f in self.ini.get(section):
if f == vd:
continue
folder = self.substituteFolder(vd + ':/' + f)
if not os.path.isdir(folder):
print 'remove entry from ini folders section %s: %s (%s)'% (section, f, folder)
self.ini.delete(section, f)
elif not self.acceptFileName(f):
print 'remove entry from ini folders section %s: %s (%s)(invalid folder name)'% (section, f, folder)
self.ini.delete(section, f)
self.ini.writeIfChanged()
def cleanupIniFilesSection(self, section, vd):
"""cleanup the current ini files ... section (for non existing files)
"""
for f in self.ini.get(section):
filename = self.substituteFolder(vd + ':/' + f)
trunk, ext = os.path.splitext(f)
if not self.acceptExtension(ext):
print 'remove entry from ini files section %s: %s (%s)(invalid extension)'% (section, f, filename)
self.ini.delete(section, f)
elif not self.acceptFileName(trunk):
print 'remove entry from ini files section %s: %s (%s)(invalid filename)'% (section, f, filename)
self.ini.delete(section, f)
elif not os.path.isfile(filename):
print 'remove entry from ini files section %s: %s (%s)'% (section, f, filename)
self.ini.delete(section, f)
self.ini.writeIfChanged()
def removeObsoleteIniSections(self, prefix, validPostfixes):
"""remove sections that do NOT conform to prefix+ one of the postfixes
(these were in "track files virtualdrives" or in "track folders virtualdrives"
but have been removed in the inifile definition)
"""
prefix = prefix.strip() + " "
for section in self.ini.get():
if not section.startswith(prefix):
continue
for postfix in validPostfixes:
if section == prefix + postfix:
break
else:
print '_folders grammar, deleting ini file section: %s'% section
self.ini.delete(section)
self.ini.writeIfChanged()
def acceptFileInFilesDict(self, vd, realfolder, filename):
"""check validity of filename in subfolder and put/remove in/from inifile
add to filesDict if applicable
"""
f = filename
trunk, ext = os.path.splitext(f)
if not self.acceptExtension(ext):
return
if not self.acceptFileName(trunk):
return
section = self.trackFilesSection
spoken = self.ini.getList(section, f, ['xpqzyx'])
spoken = filter(None, spoken)
if spoken == ['xpqzyx'] or not spoken:
spoken = [trunk]
# skip if error in inivars:
try:
self.ini.set(section, f, spoken)
except inivars.IniError:
return
if not spoken: return
for sp in spoken:
self.filesDict[sp] = vd + ':/' + f
def gotResults_siteshort(self,words,fullResults):
"""switch to last mentioned site in the list
mainly for private use, a lot of folders reside in the root folder,
siteRoot. They all have an input folder and a output folder.
"""
if self.lastSite:
words.insert(1, self.lastSite)
print 'lastSite: %s'% words
self.gotResults_site(words, fullResults)
else:
self.DisplayMessage('no "lastSite" available yet')
def gotResults_setenvironmentfolders(self,words,fullResults):
"""switch to last mentioned site in the list
mainly for private use, a lot of folders reside in the root folder,
siteRoot. They all have an input folder and a output folder.
"""
reverseOldValues = {'ignore': []}
for k in self.ini.get('folders'):
val = self.ini.get('folders', k)
if val:
reverseOldValues.setdefault(val, []).append(k)
else:
reverseOldValues['ignore'].append(k)
reverseVirtualDrives = {}
for k in self.ini.get('virtualdrives'):
val = self.ini.get('virtualdrives', k)
reverseVirtualDrives.setdefault(val, []).append(k)
## print reverseOldValues
allFolders = self.envDict() # natlinkcorefunctions.getAllFolderEnvironmentVariables()
kandidates = {}
ignore = reverseOldValues['ignore']
for (k,v) in allFolders.items():
kSpeakable = k.replace("_", " ")
if k in ignore or kSpeakable in ignore:
continue
oldV = self.ini.get('folders', k, "") or self.ini.get('folders', kSpeakable)
if oldV:
vPercented = "%" + k + "%"
if oldV == v:
continue
elif oldV == vPercented:
kPrevious = reverseOldValues[vPercented]
## print 'vPercented: %s, kPrevious: %s'% (vPercented, kPrevious)
if vPercented in reverseOldValues:
if k in kPrevious or kSpeakable in kPrevious:
continue
else:
print 'already in there: %s (%s), but spoken form changed to %s'% \
(k, v, kPrevious)
continue
else:
print 'different for %s: old: %s, new: %s'% (k, oldV, v)
kandidates[k] = v
count = len(kandidates)
if not kandidates:
self.DisplayMessage("no new environment variables to put into the folders section")
return
mes = ["%s new environment variables for your folders section of the grammar _folders"% count]
Keys = kandidates.keys()
Keys.sort()
for k in Keys:
mes.append("%s\t\t%s"% (k, kandidates[k]))
mes.append('\n\nDo you want these new environment variables in your folders section?')
if YesNo('\n'.join(mes)):
for (k,v) in kandidates.items():
if k.find('_') > 0:
kSpeakable = k.replace("_", " ")
if self.ini.get('folders', k):
self.ini.delete('folders', k)
else:
kSpeakable = k
self.ini.set('folders', kSpeakable, "%" + k + "%")
self.ini.write()
self.DisplayMessage('added %s entries, say "Show|Edit folders" to browse'% count)
else:
self.DisplayMessage('nothing added, command canceled')
def gotResults_website(self,words,fullResults):
"""start webbrowser, websites in inifile unders [websites]
if www. is not given insert, if http:// is not given insert it.
so if you have https:// or eg qh.antenna.nl you MUST insert https:// or http://
"""
site = self.getFromInifile(words, 'websites')
if site.startswith("http:") or site.startswith("https:"):
pass
else:
if not site.startswith("www."):
site = "http://www." + site
else:
site = "http://"+site
if ((site.startswith('http:') or site.startswith('https:')) and
site.find('\\') > 0):
site = site.replace('\\', '/')
if self.nextRule == 'websitecommands':
self.wantedWebsite = site
else:
self.openWebsiteDefault(site)
self.wantedWebsite = None
def gotResults_thiswebsite(self,words,fullResults):
"""get current website and open with websitecommands rule
"""
natqh.saveClipboard()
action('SSK {alt+d}{extend}{shift+exthome}{ctrl+c}')
action("VW")
self.wantedWebsite = natqh.getClipboard()
print 'this website: %s'% self.wantedWebsite
natqh.restoreClipboard()
def gotResults_websitecommands(self,words,fullResults):
"""start webbrowser, specified
expect self.wantedWebsite to be filled.
open with list in inifile, expected right hand sides to be browsers
"""
if not self.wantedWebsite:
print 'websitecommands, no valid self.wantedWebsite: %s'% self.wantedWebsite
openWith, owIndex = self.hasCommon(words, ['open with'], withIndex=1)
if openWith:
openWith = self.getFromInifile(words[owIndex+1], 'websiteopenprograms', noWarning=1)
self.openWebsiteDefault(self.wantedWebsite, openWith=openWith)
def gotResults_folder(self, words, fullResults):
"""collects the given command words and try to find the given folder
"""
## print '-------folder words: %s'% words
if self.activeFolder and words[1] in self.subfoldersDict:
subfolder = self.subfoldersDict[words[1]]
folder = os.path.join(self.activeFolder, subfolder)
print 'subfolder: %s'% folder
else:
subfolder = None
folder1 = self.foldersDict[words[1]]
folder = self.substituteFolder(folder1)
# if no next rule, simply go:
if not self.nextRule:
# do action straight away:
self.gotoFolder(folder)
self.wantedFolder = None
else:
self.wantedFolder = folder
def gotResults_site(self,words,fullResults):
"""switch to one of the sites in the list
mainly for private use, a lot of folders reside in the root folder,
siteRoot. They all have an input folder and a output folder.
"""
print 'site: %s'% words
siteSpoken = words[1]
self.lastSite = None # name of site
if siteSpoken in self.sitesDict:
siteName = self.sitesDict[siteSpoken]
self.lastSite = siteName
else:
raise ValueError("no siteName for %s"% siteSpoken)
self.site = self.getSiteInstance(siteName)
if siteName in self.sitesInstances:
self.site = self.sitesInstances[siteName]
else:
site = self.getSiteInstance(siteName)
if site:
self.sitesInstances[siteName] = site
self.lastSite = siteName
self.site = site
else:
self.site = None
print 'could not get site: %s'% siteName
#
#if site is None:
# print 'invalid site: %s, marking in ini file'% site
# self.ini.set('sites', siteName, '')
# self.ini.write()
# return
if not self.nextRule:
if self.site:
rootDir = self.site.rootDir
self.gotoFolder(rootDir)
return
elif self.nextRule == "sitecommands":
print 'site, waiting for sitecommands'
else:
self.wantedFolder = self.site.rootDir
def gotResults_sitecommands(self, words, fullResults):
"""do the various options for sites (QH special).
Assume lastSite is set
"""
if not self.site:
print "sitecommands, no last or current site set"
return
print 'sitecommands for "%s": %s (site: %s)'% (self.lastSite, words, self.site)
site = self.site
website, folder = None, None
for command in words:
command = self.getFromInifile(words[0], 'sitecommands')
if command == 'input':
print 'input: %s'% words
folder = str(site.sAbs)
elif command == 'output':
folder = str(site.hAbs)
elif command == 'local':
website = os.path.join(str(site.hAbs), 'index.html')
elif command == 'online':
sitePrefix = site.sitePrefix
if type(sitePrefix) == types.DictType:
for k, v in sitePrefix.iteritems():
sitePrefix = v
break
website = os.path.join(str(sitePrefix), 'index.html')
elif command == 'testsite':
if 'sg' in self.sitesInstances:
testsite = self.sitesInstances['sg']
else:
testsite = self.getSiteInstance('sg')
if testsite:
self.sitesInstances['sg'] = testsite
if testsite:
# site at sitegen site:
website = os.path.join(str(testsite.sitePrefix['nl']), self.lastSite, 'index.html')
if self.nextRule:
if folder:
self.wantedFolder = folder
return
elif website:
self.wantedWebsite = website
return
else:
print 'no valid folder or website for nextRule'
return
elif folder:
self.gotoFolder(folder)
self.wantedFolder = None
elif website:
self.openWebsiteDefault(website)
self.wantedWebsite = None
def getSiteInstance(self, siteName):
"""return pageopen function of site instance, or None
"""
try:
site = __import__(siteName)
except ImportError:
import traceback
print 'cannot import module %s'% siteName
print traceback.print_exc()
print 'sys.path: %s'% sys.path
return
if 'pagesopen' in dir(site):
try:
po = site.pagesopen()
return po
except:
print '"pagesopen" failed for site %s'% siteName
return
else:
print 'no function "pagesopen" in module: %s'% siteName
return
def findFolderWithIndex(self, root, allowed, ignore=None):
"""get the first folder with a file index.html"""
for i in allowed:
tryF = os.path.join(root, i)
if os.path.isdir(tryF) and (
os.path.isfile(os.path.join(tryF, 'index.html')) or \
os.path.isfile(os.path.join(tryF, 'index.txt'))):
return tryF
if ignore and type(ignore) == types.ListType:
# look in listdir and take first that is not to be ignored:
try:
List = os.listdir(root)
except:
return
for d in List:
if d in ignore:
continue
tryF = os.path.join(root, d)
if os.path.isdir(tryF) and os.path.isfile(os.path.join(tryF, 'index.html')):
return tryF
def gotResults_folder(self, words, fullResults):
"""collects the given command words and try to find the given folder
"""
## print '-------folder words: %s'% words
if self.activeFolder and words[1] in self.subfoldersDict:
subfolder = self.subfoldersDict[words[1]]
folder = os.path.join(self.activeFolder, subfolder)
print 'subfolder: %s'% folder
else:
subfolder = None
folder1 = self.foldersDict[words[1]]
folder = self.substituteFolder(folder1)
if self.nextRule == "foldercommands":
self.wantedFolder = folder
else:
self.gotoFolder(folder)
self.wantedFolder = None
def gotResults_foldercommands(self, words, fullResults):
"""open the folder and do additional actions
the optionalfoldercommands (like new or paste) must appear in the
right hand side of the inifile section (ie the value) (so spoken may be
different)
"""
if not self.wantedFolder:
print 'rule foldercommands, no wantedFolder, return'
return
kw = {}
for w in words:
opt = self.getFromInifile(w, 'foldercommands')
if opt:
if opt in self.optionalfoldercommands:
kw[opt] = opt
elif opt.startswith('subversion '):
opt = opt[11:]
kw['subversion'] = opt
else:
kw[w] = opt
#print 'folderoptions: %s'% folderoptions
#for opt in folderoptions:
# kw[opt.capitalize()] = opt
Remote, remoteIndex = self.hasCommon(words, ['on'], withIndex=1)
#print 'paste: %s, remote: %s, remoteIndex: %s'% (Paste, Remote, remoteIndex)
if Remote:
remoteLetter = self.getFromInifile(words[remoteIndex+1], 'letters')
print 'remoteLetter: %s'% remoteLetter
kw['remote'] = remoteLetter
Subversion, svnIndex = self.hasCommon(words, ['subversion'], withIndex=1)
if Subversion:
svnCommand = self.getFromInifile(words[svnIndex+1], 'subversionfoldercommands')
kw['subversion'] = svnCommand
self.gotoFolder(self.wantedFolder, **kw)
def get_active_explorer(self):
handle = win32gui.GetForegroundWindow()
shell = Dispatch("Shell.Application")
for window in shell.Windows():
if int(window.HWND) == int(handle):
return window
print "_folders: no active explorer."
return None
def get_current_directory(self):
window = self.get_active_explorer()
if window is None:
return
path = urllib.unquote(window.LocationURL)
for prefix in ["file:///", "http://"]:
if path.startswith(prefix):
lenprefix = len(prefix)
path = path[lenprefix:]
return path
def get_selected_paths(self):
window = self.get_active_explorer()
if window is None:
print 'get_selected_paths, cannot find application'
return
items = window.Document.SelectedItems()
paths = []
for item in collection_iter(items):
paths.append(item.Path)
return paths
def get_selected_filenames(self):
paths = self.get_selected_paths()
if paths is None:
return
return [os.path.basename(p) for p in paths]
def gotResults_thisfile(self, words, fullResults):
print 'filenames: %s'% self.get_selected_filenames()
paths = self.get_selected_paths()
if paths:
self.wantedFile = paths[0]
else:
print 'cannot find "thisfile"'
return
print 'wantedFile: %s'% self.wantedFile
#self.wantedFile = self.getActiveFile()
if not (self.wantedFile and os.path.isfile(self.wantedFile)):
print 'cannot get thisfile for further processing: %s'% self.wantedFile
#self.gotoFile(self.get_selected_paths()[0], False, False, False, False, False, False,
# OpenWith=openWithProgram)
# deze regel print de naam van de huidige module in het debug-venster
def gotResults_disc(self,words,fullResults):
## print '-------drive words: %s'% words
letter = self.getFromInifile(words, 'letters')
if letter:
f = letter + ":\\"
else:
print '_folders, ruls disc, no letter provided: %s'% words
return
if self.nextRule == 'foldercommands':
self.wantedFolder = f
else:
self.gotoFolder(f)
self.wantedFolder = None
def gotResults_file(self,words,fullResults):
"""collects the given command words and try to find the given file
"""
File = None
if self.activeFolder and words[1] in self.subfilesDict:
print "given file dictation " + words[1]
File = self.subfilesDict[words[1]]
print "actual filename " + File
extension =self.getFromInifile(words, 'extensions', noWarning=1)
if extension:
File, old_extension =os.path.splitext (File)
File = File +'.' + extension
File = os.path.join(self.activeFolder, File)
if not os.path.isfile(File):
File = None
print 'file from subfileslist: %s'% file
if not File:
File = self.filesDict[words[1]]
File = self.substituteFolder(File)
print "actual filename (fixed fileslist)" + File
extension =self.getFromInifile(words, 'extensions', noWarning=1)
if extension:
File, old_extension =os.path.splitext (File)
File = File +'.' + extension
if not os.path.isfile(File):
print 'invalid file: %s'% File
return
if self.nextRule == "filecommands":
self.wantedFile = File
else:
self.gotoFile(File)
self.wantedFile = None
def gotResults_filecommands(self, words, fullResults):
if not self.wantedFile:
print 'rule filecommands, no wantedFile, return'
return
print 'filecommands: %s'% words
kw = {}
for w in words:
opt = self.getFromInifile(w, 'filecommands')
if opt:
if opt in self.optionalfoldercommands:
kw[opt] = opt
elif opt.startswith('subversion '):
opt = opt[11:]
kw['subversion'] = opt
else:
kw[w] = opt
#print 'folderoptions: %s'% folderoptions
#for opt in folderoptions:
# kw[opt.capitalize()] = opt
Remote, remoteIndex = self.hasCommon(words, ['on'], withIndex=1)
#print 'paste: %s, remote: %s, remoteIndex: %s'% (Paste, Remote, remoteIndex)
if Remote:
remoteLetter = self.getFromInifile(words[remoteIndex+1], 'letters')
print 'remoteLetter: %s'% remoteLetter
kw['remote'] = remoteLetter
OpenWith, owIndex = self.hasCommon(words, ['open with'], withIndex=1)
if OpenWith:
OpenWith = self.getFromInifile(words[owIndex+1], 'fileopenprograms')
print 'openwith: %s'% OpenWith