-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsublime_pyside.py
More file actions
1198 lines (904 loc) · 33.7 KB
/
sublime_pyside.py
File metadata and controls
1198 lines (904 loc) · 33.7 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
# -*- coding: utf8 -*-
# Copyright (C) 2012 - Oscar Campos <oscar.campos@member.fsf.org>
# This plugin is Free Software see LICENSE file for details
"""
Sublime PySide adds support for Digia's PySide and Riberbancks PyQt libraries
"""
import os
import sys
import shutil
import functools
import threading
import subprocess
from glob import glob
import sublime
import sublime_plugin
try:
import rope
import ropemate
assert ropemate
from rope.base.exceptions import RopeError, ResourceNotFoundError
ROPE_SUPPORT = True
except ImportError:
ROPE_SUPPORT = False
if sys.version_info < (3, 3):
from converter import pyqt2pyside, pyside2pyqt
from converter.base import sip_api_2
SUBLIME_TEXT_3 = False
else:
from PySide.converter import pyqt2pyside, pyside2pyqt
from PySide.converter.base import sip_api_2
SUBLIME_TEXT_3 = True
# =============================================================================
# Sublime Plugin subclasses
# =============================================================================
class CreateQtProjectCommand(sublime_plugin.WindowCommand):
"""
Creates a new PySide/PyQt4 application from a template
"""
def __init__(self, window):
"""Constructor
"""
sublime_plugin.WindowCommand.__init__(self, window)
self.window = window
def run(self):
"""WindowCommand entry point
"""
CreateQtProjectThread(self.window).start()
class ConvertPyQt42PySideCommand(sublime_plugin.TextCommand):
"""Converts a PyQt4 buffer to PySide syntax
"""
def __init__(self, *args, **kwargs):
sublime_plugin.TextCommand.__init__(self, *args, **kwargs)
def run(self, edit):
"""Run the command"""
if SUBLIME_TEXT_3 is False:
PyQt42PySideWorker(self.view).start()
else:
PyQt42PySideWorker(self.view, edit).run()
def is_enabled(self):
"""Determine if this command is enabled
"""
if 'from PyQt4' in self.view.substr(
sublime.Region(0, self.view.size())
):
return True
return False
class ConvertPySide2PyQt4Command(sublime_plugin.TextCommand):
"""Converts a PySide buffer to PyQt4 syntax
"""
def __init__(self, *args, **kwargs):
sublime_plugin.TextCommand.__init__(self, *args, **kwargs)
def run(self, edit):
"""Run the command
"""
if SUBLIME_TEXT_3 is False:
PySide2PyQt4Worker(self.view).start()
else:
PySide2PyQt4Worker(self.view, edit).run()
def is_enabled(self):
"""Determine if this command is enabled
"""
if 'from PySide' in self.view.substr(
sublime.Region(0, self.view.size())
):
return True
return False
class OpenFileInDesignerCommand(sublime_plugin.WindowCommand):
"""Open the actual view buffer in Qt Designer if is a valid ui file
"""
def run(self):
"""Run the command
"""
command = QtDesignerCommand(self.window)
command.open_file_in_designer()
def is_enabled(self):
"""Determine if this command is enbaled in determinate conditions
"""
if self.window.active_view() is None:
return False
file_name = self.window.active_view().file_name()
if file_name is not None:
return self.window.active_view().file_name().endswith('.ui')
return False
class NewDialogCommand(sublime_plugin.WindowCommand):
"""Create a new dialog with buttons at bottom for QtDesigner
"""
def run(self, dirs=[]):
"""Run the command
"""
command = QtDesignerCommand(self.window)
command.new_dialog(dirs, buttons=True, position='right')
def is_enabled(self):
"""Determine if this command is enbaled in determinate conditions
"""
designer = get_settings('sublimepyside_qt_tools_map').get('designer')
if designer is None:
return False
return True
class OpenQdbusviewerCommand(sublime_plugin.WindowCommand):
"""Open the QDbusViewer application
"""
def run(self):
"""Run the command
"""
QDBusViewerCommand()
class OpenLinguistCommand(sublime_plugin.WindowCommand):
"""Open the Qt Linguist application
"""
def run(self):
"""Run the command
"""
LinguistCommand().open_linguist()
class OpenInLinguistCommand(sublime_plugin.WindowCommand):
"""Open a TS or QM file with Qt Linguist
"""
def run(self):
"""Run the command
"""
LinguistCommand().open_file_in_linguist(self.window.active_view())
def is_enabled(self):
"""Determine if this command is enabled or not
"""
if (self.window.active_view() is not None and (
self.window.active_view().file_name().endswith('.ts')
or self.window.active_view().file_name().endswith('.qm'))):
return True
return False
class GenerateTranslationsCommand(sublime_plugin.WindowCommand):
"""Generate Qt Linguist TS files
"""
def run(self, files=[], dirs=[]):
"""Run the command
"""
if not files and not dirs:
sublime.error_message(
'You have to call this function from the side bar context menu'
)
return
PySideLupdateCommand(self.window).generate_translations(files, dirs)
def is_enabled(self, files=[], dirs=[]):
"""Determine if the command is enabled
"""
if files:
for filename in files:
if filename.endswith('.py') or filename.endswith('.pro'):
return True
for dirname in dirs:
for filename in glob('{}/{}'.format(dirname, '*[.py,.pro]')):
if filename.endswith('.py') or filename.endswith('.pro'):
return True
return False
class CompileCommons:
"""Compile commons methods and parameters
"""
def is_enabled(self, files=[]):
"""Determine if a command is enabled
"""
if not files:
if (not self.window.active_view() or not
self.window.active_view().file_name().endswith(self.ext)):
return False
else:
for filename in files:
if not filename.endswith(self.ext):
return False
return True
class CompileResourceCommand(sublime_plugin.WindowCommand, CompileCommons):
"""Compile Qt Resources
"""
def run(self, files=[]):
"""Run the command
"""
if not files:
if (not self.window.active_view() or not
self.window.active_view().file_name().endswith('.qrc')):
sublime.error_message(
'This command will process QRC files only.'
)
else:
RCCCommand(self.window).compile()
else:
for filename in files:
RCCCommand(self.window).compile(filename)
def is_enabled(self, files=[]):
"""Determine if the command is enabled
"""
self.ext = '.qrc'
return CompileCommons.is_enabled(self, files)
class CompileUiCommand(sublime_plugin.WindowCommand, CompileCommons):
"""Compile Qt UI files
"""
def run(self, files=[]):
"""Run the command
"""
if not files:
PyUicCommand(self.window).compile()
else:
for filename in files:
PyUicCommand(self.window).compile(filename)
def is_enabled(self, files=[]):
"""Determine if the command is enabled
"""
self.ext = '.ui'
return CompileCommons.is_enabled(self, files)
class PreviewUiCommand(sublime_plugin.WindowCommand):
"""Preview an UI file
"""
def run(self):
"""Run the command
"""
PyUicCommand(self.window).preview()
def is_enabled(self):
"""Determine if the command is enabled
"""
if self.window.active_view() is not None:
if self.window.active_view().file_name().endswith('.ui'):
return True
return False
# =============================================================================
# Thread working classes
# =============================================================================
class CreateQtProjectThread(threading.Thread):
"""
Worker that creates a new application from a template
"""
def __init__(self, window):
self.window = window
self.tplmanager = TplManager(
sublime.packages_path(),
get_settings('sublimepyside_package'),
get_settings('sublimepyside_data_dir')
)
self.folders = self.window.folders()
self.proj_dir = None
self.proj_name = None
self.proj_library = get_settings('sublimepyside_library')
self.library_options = ['Use Digia\'s PySide', 'Use RiverBank PyQt4']
threading.Thread.__init__(self)
def run(self):
"""
Starts the thread
"""
def show_quick_pane():
"""Just a wrapper to get set_timeout on OSX and Windows"""
if not self.tplmanager.get_template_list():
sublime.error_message(
"{0}: There are no templates to list.".format(__name__))
return
self.window.show_quick_panel(
list(self.tplmanager.get_template_list()), self.tpl_selected)
sublime.set_timeout(show_quick_pane, 10)
def tpl_selected(self, picked):
"""
This method is called when user pickup a template from list
"""
if picked == -1:
return
tpl_list = list(self.tplmanager.get_template_list())
self.tplmanager.selected = tpl_list[picked].split('::')[0]
suggest = self.folders[0] if self.folders else os.path.expanduser('~')
self.window.show_input_panel(
'Project root:', suggest, self.entered_proj_dir, None, None)
def entered_proj_dir(self, path):
"""Called when user select an option in the quick panel"""
if not os.path.exists(path):
if sublime.ok_cancel_dialog(
'{path} dont exists.\nDo you want to create it now?'.format(
path=path)):
os.makedirs(path)
else:
return
if not os.path.isdir(path):
sublime.error_message(
"{path} is not a directory".format(path=path))
return
self.proj_dir = path
self.window.show_input_panel(
'Give me a project name :', 'MyProject', self.entered_proj_name,
None, None
)
def entered_proj_name(self, name):
"""Called when the user enter the project name"""
if not name:
sublime.error_message("You must use a project name")
return
self.proj_name = name
if not get_settings('sublimepyside_library_ask', bool):
self.generate_project()
else:
self.window.show_quick_panel(
self.library_options, self.library_selected)
def library_selected(self, picked):
"""Sets the selected library or PySide if none"""
if picked == -1:
self.proj_library = 'PySide'
return
self.proj_library = 'PyQt4' if picked == 1 else 'PySide'
self.generate_project()
def generate_project(self):
"""Generate the PySide or PyQt project"""
project_library = (
PySideProject if self.proj_library == 'PySide' else PyQt4Project
)
project = project_library(
self.proj_dir, self.proj_name, self.tplmanager
)
if self.tplmanager.is_valid(self.tplmanager.get_selected()):
project.generate_project()
project.generate_st2_project()
if SUBLIME_TEXT_3 is False:
project.generate_rope_project()
subprocess.Popen(
[
sublime_executable_path(),
'--project',
'%s/%s.sublime-project' % (self.proj_dir, self.proj_name)
]
)
else:
sublime.error_message(
'Could not create Qt Project files for template "{0}"'.format(
self.tplmanager.get_selected())
)
# =============================================================================
# Sublime Text 2 specific code
# =============================================================================
if SUBLIME_TEXT_3 is False:
class ConversionWorker(threading.Thread):
"""
Base worker class for PySide <--> PyQt4 converters
This is only used in Sublime Text 2
"""
def __init__(self, view):
threading.Thread.__init__(self)
self.view = view
def run(self):
"""
Starts the thread
"""
def show_conversion_confirmation():
"""Shows a confirmation dialog and proceed if true"""
if self.__class__.__name__ == 'PyQt42PySideWorker':
library = 'PySide'
else:
library = 'PyQt4'
if sublime.ok_cancel_dialog(
'Do you really want to convert this file to %s' % library
):
self.qt_conversion()
sublime.set_timeout(show_conversion_confirmation, 10)
def qt_conversion(self):
"""Must be reimplemnted"""
raise NotImplementedError('qt_conversion not implemented yet')
# =============================================================================
# Sublime Text 3 specific code
# =============================================================================
else:
class ConversionWorker(object):
"""
Base worker class for PySide <--> PyQt4 converters
This is only used in Sublime Text 3
"""
def __init__(self, view):
self.view = view
def run(self):
"""
Starts the thread
"""
def show_conversion_confirmation():
"""Shows a confirmation dialog and proceed if true"""
if self.__class__.__name__ == 'PyQt42PySideWorker':
library = 'PySide'
else:
library = 'PyQt4'
if sublime.ok_cancel_dialog(
'Do you really want to convert this file to %s' % library
):
self.qt_conversion()
show_conversion_confirmation()
def qt_conversion(self):
"""Must be reimplemnted"""
raise NotImplementedError('qt_conversion not implemented yet')
class PyQt42PySideWorker(ConversionWorker):
"""
Worker class to convert PyQt4 buffer to PySide Syntax.
Note that there is not automatically conversion from PyQt API 1
to PySide yet so you should remove all the QVariant stuff yourself.
This class is only used in Sublime Text 2
"""
def __init__(self, view, edit=None):
ConversionWorker.__init__(self, view)
self.edit = edit
def qt_conversion(self):
"""Converts Qt code"""
pyqt2pyside.Converter(self.view).convert(self.edit)
self.remove_api_imports()
def remove_api_imports(self):
"""Remove api conversions for PyQt4 API 2"""
# line_one = self.view.find('import sip', 0)
line_one = self.view.find('# PyQT4 API 2 SetUp.', 0)
if not line_one:
line_one = self.view.find('from sip import setapi', 0)
# At this point we already changed PyQt4 occurrences to PySide
line_two = self.view.find('from PySide', 0)
if not line_two:
line_two = self.view.find('import PySide', 0)
if not line_one or not line_two:
return
region = sublime.Region(line_one.a, self.view.line(line_two).a)
edit = self.view.begin_edit() if self.edit is None else self.edit
self.view.erase(edit, region)
# self.view.insert(edit, line_one.a, '\n')
self.view.end_edit(edit)
class PySide2PyQt4Worker(ConversionWorker):
"""
Worker class to convert PySide buffer to PyQt4 Syntax.
The conversion is just to PyQt4 API 2 so if you're running Python 3
just remove the explicit api conversion lines.
This class is only used in Sublime Text 2
"""
def __init__(self, view, edit=None):
ConversionWorker.__init__(self, view)
self.edit = edit
def qt_conversion(self):
"""Converts Qt code"""
pyside2pyqt.Converter(self.view).convert(self.edit)
self.insert_api_imports()
def insert_api_imports(self):
"""Insert api conversions for PyQt4 API 2"""
pyqt4import = self.view.find('from PyQt4', 0)
if not pyqt4import:
pyqt4import = self.view.find('import PyQt4', 0)
if not pyqt4import:
return
prior_lines = self.view.lines(sublime.Region(0, pyqt4import.a))
insert_import_str = '\n' + sip_api_2 + '\n'
existing_imports_str = self.view.substr(
sublime.Region(prior_lines[0].a, prior_lines[-1].b))
if insert_import_str.rstrip() in existing_imports_str:
return
insert_import_point = prior_lines[-1].a
edit = self.edit if self.edit is not None else self.view.begin_edit()
self.view.insert(self.edit, insert_import_point, insert_import_str)
self.view.end_edit(edit)
# =============================================================================
# Classes
# =============================================================================
class Project(object):
"""
Project class for Sublime Text 2 and SublimeRope Projects
"""
def __init__(self, root, name, tplmanager):
super(Project, self).__init__()
if sublime.platform() == 'windows':
# os.path.normpath is not working
root = root.replace('\\', '/')
self.root = root
self.name = name
self.tplmanager = tplmanager
self.ropemanager = RopeManager()
self.lib = None
def generate_rope_project(self):
"""
Create Rope project structure
"""
if not self.ropemanager.is_supported():
return
self.ropemanager.create_project(self.root)
def generate_st2_project(self):
"""
Create Sublime Text 2 project file
"""
file_name = '{0}/{1}.sublime-project'.format(self.root, self.name)
with open(file_name, 'w') as fdescriptor:
template_name = '{0}/template.sublime-project'.format(
self.tplmanager.get_template_dir())
with open(template_name, 'r') as fhandler:
file_buffer = fhandler.read().replace(
'${PATH}', self.root).replace('${QT_LIBRARY}', self.lib)
fdescriptor.write(file_buffer)
def generate_project(self):
"""
Create the project files
"""
templates_dir = '{0}/{1}/*'.format(
self.tplmanager.get_template_dir(),
self.tplmanager.get_selected(True)
)
for tpl in glob(templates_dir):
path = '{0}/{1}'.format(self.root, os.path.basename(tpl))
if os.path.isdir(tpl):
sublime.status_message('Copying {0} tree...'.format(tpl))
try:
shutil.copytree(tpl, path)
except OSError as error:
if error.errno != 17:
message = '%d: %s' % (error.errno, error.strerror)
sublime.error_message(message)
continue
with open(tpl, 'r') as fhandler:
app_name = (
self.name.encode('utf-8')
if SUBLIME_TEXT_3 is False else self.name
)
file_buffer = fhandler.read().replace(
'${APP_NAME}', app_name).replace(
'${QT_LIBRARY}', self.lib).replace(
'${PyQT_API_CHECK}', self.pyqt_api_check())
with open(path, 'w') as fhandler:
fhandler.write(file_buffer)
sublime.status_message('Copying {0} file...'.format(tpl))
def pyqt_api_check(self):
"""
If PyQt4 is used then we add API 2
"""
if self.lib == 'PyQt4':
return sip_api_2
return ''
class PySideProject(Project):
"""
PySide Qt Project
"""
def __init__(self, root, name, manager):
super(PySideProject, self).__init__(root, name, manager)
self.lib = 'PySide'
class PyQt4Project(Project):
"""
PyQt4 Qt Project
"""
def __init__(self, root, name, manager):
super(PyQt4Project, self).__init__(root, name, manager)
self.lib = 'PyQt4'
class TplManager(object):
"""
SublimePySide TemplateManager class
"""
def __init__(self, packagespath, packagedir=None, datadir=None):
super(TplManager, self).__init__()
self.packagespath = packagespath
self.packagedir = packagedir
self.datadir = datadir
self.selected = None
def is_valid(self, template):
"""
Check if the given project template is valid
"""
tpl_list = list(self.get_template_list())
if template not in [tpl.split('::')[0] for tpl in tpl_list]:
return False
return True
def get_template_dir(self):
"""
Return the templates dir
"""
return '{0}/{1}/{2}/templates'.format(
self.packagespath,
self.packagedir,
self.datadir
)
def get_template_list(self):
"""
Generator for lazy templates list
"""
file_name = '{0}/templates.lst'.format(self.get_template_dir())
with open(file_name, 'r') as fhandler:
for tpl in fhandler.read().split('\n'):
if len(tpl):
tpl_split = tpl.split(':')
yield '{0}:: {1}'.format(tpl_split[0], tpl_split[1])
def get_selected(self, dir_conversion=False):
"""Return the selected template"""
return (self.selected.replace(' ', '_').lower()
if dir_conversion else self.selected)
class RopeManager(object):
"""
Manager for rope/SublimeRope features
"""
def __init__(self):
super(RopeManager, self).__init__()
self.supported = ROPE_SUPPORT
def is_supported(self):
"""Returns true if rope is supported, otherwise returns false"""
return self.supported
def create_project(self, projectroot=None):
"""
Create a new Rope project
"""
if not projectroot or not self.supported:
return
try:
rope_project = rope.base.project.Project(projectroot)
rope_project.close()
except (ResourceNotFoundError, RopeError) as error:
msg = 'Could not create rope project folder at {0}\nException: {1}'
sublime.status_message(msg.format(self.root, str(error)))
class Command(object):
"""Base class for external commands
"""
def __init__(self, command):
self.command = command
self.proc = None
def launch(self):
"""Launch the external process
"""
kwargs = {
'cwd': os.path.dirname(os.path.abspath(__file__)),
'bufsize': -1
}
if sublime.platform() == 'windows':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
kwargs['startupinfo'] = startupinfo
sub_args = [self.command] + self.options
self.proc = subprocess.Popen(sub_args, **kwargs)
class PyUicCommand(Command):
"""PySide-uic
"""
def __init__(self, window):
self.window = window
self.options = []
command = get_settings('sublimepyside_tools_map').get('uic')
if command is None:
self.is_valid = False
sublime.error_message(
'PySide-uic application path is not configured'
)
else:
self.is_valid = True
super(PyUicCommand, self).__init__(command)
def preview(self, filename=None):
"""Show a preview of the given filename
"""
if filename is None:
filename = self.window.active_view().file_name()
self.options += ['-p', filename]
self.launch()
def compile(self, filename=None):
"""Compile a UI file
"""
if filename is None:
filename = self.window.active_view().file_name()
self.options += ['-o', filename.replace('.ui', '_ui.py'), filename]
self.launch()
class RCCCommand(Command):
"""PySide-rcc
"""
def __init__(self, window):
self.window = window
self.options = []
command = get_settings('sublimepyside_tools_map').get('rcc')
if command is None:
self.is_valid = False
sublime.error_message(
'PySide-rcc application path is not configured'
)
else:
self.is_valid = True
super(RCCCommand, self).__init__(command)
def compile(self, filename=None):
"""Compile a file
"""
if filename is None:
filename = self.window.active_view().file_name()
if filename.lower().endswith('.qrc'):
rcc_options = get_settings('sublimepyside_rcc_options')
if rcc_options.get('output_file', '') != 'same_rc':
self.window.show_input_panel(
'Output filename (with no extension):',
filename.replace('.qrc', '_rc'),
lambda name: self.compile_resource_file(
filename, '{0}.py'.format(name.strip()), rcc_options
), None, None
)
else:
self.compile_resource_file(
filename, filename.replace('.qrc', '_rc.py'), rcc_options
)
else:
sublime.error_message('Unknown file extension')
def compile_resource_file(self, input_file, filename, rcc_options):
"""Process a QRC file using PySide-rcc
"""
self.options += ['-o', filename]
root_path = rcc_options.get('root_path', '')
no_compress = rcc_options.get('no_compress', False)
compression_level = rcc_options.get('compression_level', -1)
if compression_level != -1 and not no_compress:
if compression_level >= 0 and compression_level <= 9:
self.options += ['-compress', str(compression_level)]
if no_compress:
self.options.append('-no-compress')
if root_path != '' and type(root_path) is str:
self.options += ['-root', root_path]
self.options.append(input_file)
self.launch()
class LinguistCommand(Command):
"""Linguist
"""
def __init__(self):
self.options = []
command = get_settings('sublimepyside_qt_tools_map').get('linguist')
if command is None:
self.is_valid = False
sublime.error_message(
'Qt Linguist application path is not configured'
)
else:
self.is_valid = True
super(LinguistCommand, self).__init__(command)
def open_linguist(self):
"""Just open Qt Linguist
"""
self.launch()
def open_file_in_linguist(self, view):
"""Open the buffer file with linguist
"""
if (view.file_name().lower().endswith('.ts')
or view.file_name().lower().endswith('.qm')):
self.options.append(view.file_name())
self.launch()
else:
sublime.error_message('Unknown file extension...')
class PySideLupdateCommand(Command):
"""PySide Lupdate
"""
def __init__(self, window):
self.window = window
self.options = []