def press_ok(self, *args, **kwargs): # edit data dict files = self.data.get('files', {}) new = {} for k, v in self.state.items(): for n, i in enumerate(v.split(';')[1].split(',')): if i == '1': lexer = self.lexers[n] lx = new.get(lexer, []) for x in files[k]: if x not in lx: lx.append(x) new[lexer] = lx if not new: ct.msg_box( _('You must check at least one CudaText lexer, for snippets to work' ), ct.MB_OK + ct.MB_ICONWARNING) return self.data['files'] = new # install path = os.path.join(ct.app_path(ct.APP_DIR_DATA), 'snippets_vs') vs.install_vs_snips(path, self.data) ct.dlg_proc(self.h, ct.DLG_HIDE)
def do_format_ex(text, syntax): config = get_config() try: return run_node(text, [tool_js, syntax, config, '.']) except Exception as e: app.msg_box('Error while running Node.js \n' + str(e), app.MB_OK + app.MB_ICONERROR)
def check_cudatext(): fn = os.path.join(tempfile.gettempdir(), 'cudatext_download.html') app.msg_status('Downloading: '+DOWNLOAD_PAGE, True) get_url(DOWNLOAD_PAGE, fn, True) app.msg_status('') if not os.path.isfile(fn): app.msg_status('Cannot download: '+DOWNLOAD_PAGE) return text = open(fn, encoding='utf8').read() items = re.findall(DOWNLOAD_REGEX, text) if not items: app.msg_status('Cannot find download links') return items = sorted(items, key=lambda i:i[REGEX_GROUP_VER], reverse=True) print('Found links:') for i in items: print(' '+i[0]) url = items[0][0] ver_inet = items[0][REGEX_GROUP_VER] ver_local = app.app_exe_version() if versions_ordered(ver_inet, ver_local): app.msg_box('Latest CudaText is already here.\nHere: %s\nInternet: %s' %(ver_local, ver_inet), app.MB_OK+app.MB_ICONINFO) return if app.msg_box('Newer CudaText is available.\nHere: %s\nInternet: %s\n\nOpen download URL in browser?' %(ver_local, ver_inet), app.MB_YESNO+app.MB_ICONINFO) == app.ID_YES: webbrowser.open_new_tab(url) print('Opened download URL')
def dlg_import_choose_mcrs(self): l, lt = '\n', '\n ' while True: imp_file = app.dlg_file(True, '', '', 'Cuda macros|*.cuda-macros|All file|*.*') if imp_file is None: return (None, None) vers_mcrs = apx._json_loads(open(imp_file).read()) if vers_mcrs is None: if app.ID_OK != app.msg_box( 'No macros in file\n ' + imp_file + '\n\nChoose another file?', app.MB_OKCANCEL): return (None, None) continue #while vers = vers_mcrs.get('vers', {}) if (app.app_api_version() < vers.get('ver-api', app.app_api_version()) and app.ID_OK != app.msg_box( 'Macros from' + lt + imp_file + l + 'are recorded in CudaText with version' + lt + '"{}"' + l + 'Your CudaText has older version' + lt + '"{}"' + l + '' + l + 'No guarantee of correct working!' + l + '' + l + 'Continue import?'.format( vers['ver-app'], app.app_exe_version()), app.MB_OKCANCEL)): return (None, None) mcrs = vers_mcrs.get('macros', []) if 0 != len(mcrs): break #while if app.ID_OK != app.msg_box( 'No macros in file\n ' + imp_file + '\n\nChoose another file?', app.MB_OKCANCEL): return (None, None) #while True: return (imp_file, mcrs)
def wnen_menu(ag, tag): nonlocal opts, prev_wt if tag in ('prev','next'): return do_next(ag, tag) if tag in ('fpth','clos'): prev_wt = ''; opts[tag] = not opts[tag] elif tag=='help': app.msg_box(HELP_C, app.MB_OK) elif tag=='rest': ed.set_caret(*ed_crts[0]); return None return []
def check_cudatext(): fn = os.path.join(tempfile.gettempdir(), 'cudatext_download.html') app.msg_status('Downloading: '+DOWNLOAD_PAGE, True) get_url(DOWNLOAD_PAGE, fn, True) app.msg_status('') if not os.path.isfile(fn): app.msg_status('Cannot download: '+DOWNLOAD_PAGE) return text = open(fn, encoding='utf8', errors='replace').read() items = re.findall(FILE_RE, text) if not items: app.msg_status('Cannot find download links') return items = sorted(items, reverse=True) print('Found links:') for i in items: print(' '+i[0]) url = items[0][0] ver_inet = items[0][REGEX_GROUP_VER] ver_local = app.app_exe_version() if versions_ordered(ver_inet, ver_local): app.msg_box('Latest CudaText is already here.\nLocal: %s\nInternet: %s' %(ver_local, ver_inet), app.MB_OK+app.MB_ICONINFO) return if app.msg_box('CudaText update is available.\nLocal: %s\nInternet: %s\n\nOpen download URL in browser?' %(ver_local, ver_inet), app.MB_YESNO+app.MB_ICONINFO) == app.ID_YES: webbrowser.open_new_tab(url) print('Opened download URL')
def dlg_import_choose_mcrs(self): l,lt = '\n', '\n ' while True: imp_file= app.dlg_file(True, '', '', 'Cuda macros|*.cuda-macros|All file|*.*') if imp_file is None: return (None, None) vers_mcrs = apx._json_loads(open(imp_file).read()) if vers_mcrs is None: if app.ID_OK != app.msg_box('No macros in file\n '+imp_file+'\n\nChoose another file?' ,app.MB_OKCANCEL): return (None, None) continue #while vers = vers_mcrs.get('vers', {}) if (app.app_api_version() < vers.get('ver-api', app.app_api_version()) and app.ID_OK != app.msg_box( 'Macros from' +lt+imp_file +l+ 'are recorded in CudaText with version' +lt+ '"{}"' +l+ 'Your CudaText has older version' +lt+ '"{}"' +l+ '' +l+ 'No guarantee of correct working!' +l+ '' +l+ 'Continue import?'.format(vers['ver-app'], app.app_exe_version()) , app.MB_OKCANCEL)): return (None, None) mcrs = vers_mcrs.get('macros', []) if 0!=len(mcrs): break #while if app.ID_OK != app.msg_box('No macros in file\n '+imp_file+'\n\nChoose another file?' ,app.MB_OKCANCEL): return (None, None) #while True: return (imp_file, mcrs)
def dlg_import(self): ''' Show dlg for import some macros. ''' if app.app_api_version()<FROM_API_VERSION: return app.msg_status(_('Need update CudaText')) (imp_file ,mcrs) = self.dlg_import_choose_mcrs() if imp_file is None: return lmcrs = len(mcrs) WD_LST, \ HT_LST = (500 ,500) crt,sels= '0', ['1'] * lmcrs while True: cnts = ([ dict( tp='lb' ,tid='file' ,l=GAP ,w=85 ,cap=_('Import &from') ) ,dict(cid='file' ,tp='ed' ,t=GAP ,l=GAP+85 ,r=GAP+WD_LST-35 ,en='0' ) ,dict(cid='brow' ,tp='bt' ,tid='file' ,l=GAP+HT_LST-35 ,r=GAP+WD_LST ,cap=_('&...') ) ,dict(cid='mcrs' ,tp='ch-lbx',t=35 ,h=HT_LST ,l=GAP ,w= WD_LST ,items=[mcr['nm'] for mcr in mcrs] ) ,dict(cid='ch-a' ,tp='bt' ,t=GAP+35+HT_LST ,l=GAP*1 ,w=100 ,cap=_('Check &all') ) ,dict(cid='ch-n' ,tp='bt' ,t=GAP+35+HT_LST ,l=GAP*2+100 ,w=100 ,cap=_('U&ncheck all') ) ,dict(cid='impo' ,tp='bt' ,t=GAP+35+HT_LST ,l= WD_LST-70*2 ,w=70 ,cap=_('&Import') ,props='1' ) # default ,dict(cid='-' ,tp='bt' ,t=GAP+35+HT_LST ,l=GAP+WD_LST-70*1 ,w=70 ,cap=_('Close') ) ]) vals = dict( file=imp_file ,mcrs=(crt, sels) ) btn, \ vals, \ chds = dlg_wrapper(_('Import macros'), GAP+WD_LST+GAP, GAP*4+HT_LST+25*2, cnts, vals, focus_cid='mrcs') if btn is None or btn=='-': return crt,sels= vals['mcrs'] pass; LOG and log('sels={}',sels) if False:pass elif btn=='brow': #ans_s=='file': (new_imp_file ,new_mcrs) = self.dlg_import_choose_mcrs() if new_imp_file is None: continue #while imp_file = new_imp_file mcrs = new_mcrs lmcrs = len(mcrs) crt,sels = '0', ['1'] * lmcrs elif btn=='ch-a': #ans_s=='all': sels = ['1'] * lmcrs elif btn=='ch-n': #ans_s=='no': sels = ['0'] * lmcrs elif btn=='impo': #ans_s=='imp': if '1' not in sels: app.msg_box(_('Select some names'), app.MB_OK) continue (good_nms ,fail_nms) = self.import_from_list([mcr for (ind, mcr) in enumerate(mcrs) if sels[ind]=='1']) l,lt = '\n', '\n ' app.msg_box( _('Import macros:') +lt+lt.join(good_nms) +l+'' +l+_('Skip duplicates:') +lt+lt.join(fail_nms) ,app.MB_OK)
def report_to_html(self): if app_name=='CudaText' and app.app_api_version()<'1.0.105': app.msg_box('Plugin needs newer app version', app.MB_OK) return htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name)) do_report(htm_file) webbrowser.open_new_tab('file://'+htm_file) app.msg_status('Opened browser with file '+htm_file)
def on_macro(self, ed_self, mcr_record): ''' Finish for macro-recording. Params mcr_record "\n"-separated list of number number,string py:string_module,string_method,string_param ''' pass; LOG and log('mcr_record={}',mcr_record) if ''==mcr_record: return app.msg_status('Empty record') def_nm = '' nms = [mcr['nm'] for mcr in self.macros] for num in range(1,1000): def_nm = 'Macro{}'.format(num) if def_nm not in nms: break #for num while True: mcr_nm = app.dlg_input('Macro name. Tricks: "!NM" overwrite NM, "=NM" show NM in dialog', def_nm) if mcr_nm is None: return mcr_nm = mcr_nm.strip() if ''==mcr_nm: continue #while if mcr_nm[0]=='=': self.need_dlg = True mcr_nm = mcr_nm[1:] use_old = False if ''==mcr_nm: continue #while if mcr_nm[0]=='!': use_old = True mcr_nm = mcr_nm[1:] if ''!=mcr_nm: break #while pass; LOG and log('self.need_dlg, use_old, mcr_nm={}',(self.need_dlg, use_old, mcr_nm)) if use_old and mcr_nm in nms: mcr_ind = nms.index(mcr_nm) self.macros[mcr_ind]['rec'] = mcr_record self.macros[mcr_ind]['evl'] = self._record_data_to_cmds(mcr_record) id4mcr = self.macros[mcr_ind]['id'] else: while mcr_nm in nms: app.msg_box('Select other name.\nMacros names now:\n\n'+'\n'.join(nms), app.MB_OK) mcr_nm = app.dlg_input('Macro name', mcr_nm) if mcr_nm is None: return id4mcr = random.randint(10000, 99999) while id4mcr in self.mcr4id: id4mcr = random.randint(10000, 99999) self.macros += [{'id' :id4mcr ##?? conflicts? ,'nm' :mcr_nm ,'rec':mcr_record ,'evl':self._record_data_to_cmds(mcr_record) }] self._do_acts() if self.need_dlg: self.need_dlg = False self.last_mcr_id= id4mcr self.dlg_config()
def ins_default(self): fmt = get_default_format() if not fmt: app.msg_box( 'No default time format is specified. To specify it, open config file (menu Options / Settings-plugins / Insert Time), and prefix some format with @ char.', app.MB_OK or app.MB_ICONINFO) return self.do_insert(do_format(fmt))
def report_to_html(self): # if app_name=='CudaText' and app.app_api_version()<'1.0.105': if app_name=='CudaText' and app.app_api_version()<'1.0.212': # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN app.msg_box(_('Plugin needs newer app version'), app.MB_OK) return htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name)) do_report(htm_file) webbrowser.open_new_tab('file://'+htm_file) app.msg_status(_('Opened browser with file ')+htm_file)
def compact_to_tab(self): if app_name=='CudaText' and app.app_api_version()<'1.0.212': # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN app.msg_box('Plugin needs newer app version', app.MB_OK) return plain_rpt = get_str_report() if False:pass elif app_name=='CudaText': app.file_open('') ed.set_text_all(plain_rpt) elif app_name=='SynWrite': pass
def compact_to_tab(self): if app_name=='CudaText' and app.app_api_version()<'1.0.212': # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN app.msg_box(_('Plugin needs newer app version'), app.MB_OK) return plain_rpt = get_str_report() if False:pass elif app_name=='CudaText': app.file_open('') ed.set_text_all(plain_rpt) elif app_name=='SynWrite': pass
def download(url, file_name=TEMPFILE): """Download extension by url, and save into file_name""" with open(file_name, "wb") as f: r = requests.get(url) if r.status_code == 200: f.write(r.content) else: ct.msg_box( _("Can't download this package.\nStatus code {}").format( r.status_code), ct.MB_OK + ct.MB_ICONERROR) return return prepare_vs_snips(file_name)
def __init__(self): self.cfg = Setting() self.parser = Parser() self.change_parser() self.date = Date() if MYLEXER not in ct.lexer_proc(ct.LEXER_GET_LEXERS, ''): ct.msg_box( 'Plugin "Plain Tasks" could not find it\'s required lexer ToDo.' + ' Please install this lexer from "Plugins / Addon Manager / Install" and restart CudaText.', ct.MB_OK + ct.MB_ICONERROR)
def run_app(text, syntax): command = [ PROGRAM, '-l', syntax, '-c', get_config_filename('Uncrustify'), '--set', 'newlines=LF', ] print('Running:', ' '.join(command)) content = text.encode("utf-8") try: if os.name == 'nt': # to hide the console window brings from command si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW # si.wShowWindow = subprocess.SW_HIDE # this is default provided proc = subprocess.Popen(command, \ stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, startupinfo = si) else: proc = subprocess.Popen(command, \ stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) outs, errs = proc.communicate(input=content) ret_code = proc.poll() if ret_code != 0: if errs: msg = errs.decode("utf-8") # slice the last useless part if found (from Uncrustify) pos = msg.find("Try running with -h for usage information") err = "Uncrustify failed (0x%X)\n\n%s" % (ret_code, msg[:pos]) else: err = "Uncrustify stopped (0x%X)" % ret_code app.msg_box(err, app.MB_OK + app.MB_ICONWARNING) return except (OSError, ValueError, subprocess.CalledProcessError, Exception) as e: err = "Cannot execute '%s':\n\n%s" % (command[0], e) app.msg_box(err, app.MB_OK + app.MB_ICONERROR) return formatted_code = outs.decode("utf-8") return formatted_code
def dlg_export(self): ''' Show dlg for export some macros. ''' if app.app_api_version()<FROM_API_VERSION: return app.msg_status(_('Need update CudaText')) if 0==len(self.macros): return app.msg_status(_('No macros for export')) exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros') exp_file= '' if exp_file is None else exp_file exp_file= exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros') (WD_LST ,HT_LST)= (500 ,500) lmcrs = len(self.macros) crt,sels= '0', ['0'] * lmcrs while True: pass; LOG and log('sels={}',sels) cnts = ([ dict( tp='lb' ,tid='file' ,l=GAP ,w=70 ,cap=_('Export &to') ) ,dict(cid='file' ,tp='ed' ,t=GAP ,l=GAP+70 ,r=GAP+WD_LST-35 ,en='0' ) ,dict(cid='brow' ,tp='bt' ,tid='file' ,l=GAP+HT_LST-35 ,r=GAP+WD_LST ,cap=_('&...') ) ,dict(cid='mcrs' ,tp='ch-lbx',t=35 ,h=HT_LST ,l=GAP ,w= WD_LST ,items=[mcr['nm'] for mcr in self.macros]) ,dict(cid='ch-a' ,tp='bt' ,t=GAP+35+HT_LST ,l=GAP*1 ,w=100 ,cap=_('Check &all') ) ,dict(cid='ch-n' ,tp='bt' ,t=GAP+35+HT_LST ,l=GAP*2+100 ,w=100 ,cap=_('U&ncheck all') ) ,dict(cid='expo' ,tp='bt' ,t=GAP+35+HT_LST ,l= WD_LST-70*2 ,w=70 ,cap=_('&Export') ,props='1' ) # default ,dict(cid='-' ,tp='bt' ,t=GAP+35+HT_LST ,l=GAP+WD_LST-70*1 ,w=70 ,cap=_('Close') ) ]) vals = dict( file=exp_file ,mcrs=(crt, sels) ) btn, \ vals, \ chds = dlg_wrapper(_('Export macros') ,GAP+WD_LST+GAP, GAP*5+HT_LST+25*2-GAP, cnts, vals, focus_cid='mrcs') if btn is None or btn=='-': return crt,sels= vals['mcrs'] pass; LOG and log('sels={}',sels) if False:pass elif btn=='brow': #ans_s=='file': new_exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros') if new_exp_file is not None: exp_file = new_exp_file exp_file = exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros') elif btn=='ch-a': #ans_s=='all': sels = ['1'] * lmcrs elif btn=='ch-n': #ans_s=='no': sels = ['0'] * lmcrs elif btn=='expo': #ans_s=='exp': if '1' not in sels: app.msg_box(_('Select some names'), app.MB_OK) continue self.export_to_file(exp_file, [mcr for (ind, mcr) in enumerate(self.macros) if sels[ind]=='1']) return
def do_format_ex(text, is_css): fn = get_config_filename('CSS AutoPrefixer') s = open(fn, 'r').read() #del // comments s = re.sub(r'(^|[^:])//.*', r'\1', s) opt = json.loads(s) opt['is_css'] = is_css opt = json.dumps(opt) try: return run_node(text, [tool_js, opt]) except Exception as e: app.msg_box('Error while running Node.js \n' + str(e), app.MB_OK + app.MB_ICONERROR)
def open(self, ssnew=None): ''' Open new session from file ssnew or after user asking ''' if not _checkAPI(): return # in_dir = app.app_path(app.APP_DIR_DATA) sscur = app.app_path(app.APP_FILE_SESSION) sscur_save = app.app_proc(app.PROC_SAVE_SESSION, sscur) pass #LOG and log('sscur_save={}',(sscur_save)) if sscur_save == False: return if ssnew is None: ssnew = app.dlg_file( is_open=True, filters=DLG_ALL_FILTER, init_filename='!' # '!' to disable check "filename exists" , init_dir='') if ssnew is None: return if ssnew.endswith(SWSESS_EXT) and os.path.isfile(ssnew): # Import from Syn sssyn = ssnew sscud = ssnew[:-len(SWSESS_EXT)] + CDSESS_EXT if os.path.isfile(sscud): sscud = app.dlg_file(is_open=False, filters=DLG_CUD_FILTER, init_filename=os.path.basename(sscud), init_dir=os.path.dirname(sscud)) if not sscud: return if not import_syn_sess(sssyn, sscud): return ssnew = sscud pass #LOG and log('ssnew={}',(ssnew)) ssnew = apx.icase(False, '', ssnew.endswith(CDSESS_EXT), ssnew, os.path.isfile(ssnew), ssnew, True, ssnew + CDSESS_EXT) pass #LOG and log('ssnew={}',(ssnew)) if os.path.isfile(ssnew): # Open # app.app_proc(app.PROC_SAVE_SESSION, sscur) ssnew_load = app.app_proc(app.PROC_LOAD_SESSION, ssnew) pass #LOG and log('ssnew_load={}',(ssnew_load)) if ssnew_load == False: return app.app_proc(app.PROC_SET_SESSION, ssnew) app.msg_status(OPENED.format(stem=juststem(ssnew))) self.top_sess(ssnew) else: # New if app.ID_NO == app.msg_box( CREATE_ASK.format(stem=juststem(ssnew)), app.MB_YESNO): return # app.app_proc(app.PROC_SAVE_SESSION, sscur) app.ed.cmd(cmds.cmd_FileCloseAll) app.app_proc(app.PROC_SET_SESSION, ssnew) app.app_proc(app.PROC_SAVE_SESSION, ssnew) app.msg_status(CREATED.format(stem=juststem(ssnew))) self.top_sess(ssnew)
def check_cudatext(): fn = os.path.join(tempfile.gettempdir(), 'cudatext_download.html') app.msg_status('Downloading: ' + DOWNLOAD_PAGE, True) get_url(DOWNLOAD_PAGE, fn, True) app.msg_status('') if not os.path.isfile(fn): app.msg_status('Cannot download: ' + DOWNLOAD_PAGE) return text = open(fn, encoding='utf8').read() items = re.findall(DOWNLOAD_REGEX, text) if not items: app.msg_status('Cannot find download links') return items = sorted(items, key=lambda i: i[1], reverse=True) print('Found links:') for i in items: print(' ' + i[0]) url = items[0][0] ver_inet = items[0][1] ver_local = app.app_exe_version() #ver_inet = '1.10.0.2' #test #ver_local = '0' #test if versions_ordered(ver_inet, ver_local): app.msg_box( 'Latest CudaText is already here\nHere: %s\nInternet: %s' % (ver_local, ver_inet), app.MB_OK + app.MB_ICONINFO) return text = '\n'.join([ 'type=label\1pos=6,20,500,0\1cap=CudaText newer version is available at this URL:', 'type=linklabel\1pos=6,45,800,0\1cap=' + url + '\1props=' + url + '\1font_size=9', 'type=button\1pos=300,100,400,0\1cap=OK\1props=1' ]) app.dlg_custom('CudaText update', 700, 132, text)
def open(self, ssnew=None): ''' Open new session from file ssnew or after user asking ''' if not _checkAPI(): return # in_dir = app.app_path(app.APP_DIR_DATA) sscur = app.app_path(app.APP_FILE_SESSION) if ssnew is None: ssnew = app.dlg_file(is_open=True, filters=DLG_ALL_FILTER , init_filename='!' # '!' to disable check "filename exists" , init_dir= '' ) if ssnew is None: return if ssnew.endswith(SWSESS_EXT) and os.path.isfile(ssnew): # Import from Syn sssyn = ssnew sscud = ssnew[:-len(SWSESS_EXT)]+CDSESS_EXT if os.path.isfile(sscud): sscud = app.dlg_file(is_open=False, filters=DLG_CUD_FILTER , init_filename=os.path.basename(sscud) , init_dir= os.path.dirname( sscud) ) if not sscud: return if not import_syn_sess(sssyn, sscud): return ssnew = sscud ssnew = apx.icase(False,'' , ssnew.endswith(CDSESS_EXT) , ssnew , os.path.isfile(ssnew) , ssnew , True , ssnew+CDSESS_EXT ) if os.path.isfile(ssnew): # Open app.app_proc(app.PROC_SAVE_SESSION, sscur) app.app_proc(app.PROC_LOAD_SESSION, ssnew) app.app_proc(app.PROC_SET_SESSION, ssnew) app.msg_status(OPENED.format(stem=juststem(ssnew))) self.top_sess(ssnew) else: # New if app.ID_NO==app.msg_box(CREATE_ASK.format(stem=juststem(ssnew)), app.MB_YESNO): return app.app_proc(app.PROC_SAVE_SESSION, sscur) app.ed.cmd(cmds.cmd_FileCloseAll) app.app_proc(app.PROC_SET_SESSION, ssnew) app.app_proc(app.PROC_SAVE_SESSION, ssnew) app.msg_status(CREATED.format(stem=juststem(ssnew))) self.top_sess(ssnew)
def _dlg_del_snip(self, *args, **vargs): ''' dlg OK|Cancel + remove from 'self.file_snippets' + queue save of snippet group file ''' #pass; print(' del snip') pkg = self._get_sel_pkg() snips_fn, lexers = self._get_sel_group(pkg) snip_name, snip = self._get_sel_snip(pkg, snips_fn) if pkg and snips_fn and snip_name and snip: res = ct.msg_box( _('Delete snippet "{0}"?').format(snip_name), ct.MB_OKCANCEL | ct.MB_ICONWARNING) if res == ct.ID_OK: snips = self.file_snippets.get((pkg['path'], snips_fn)) if snip_name in snips: # removing from snips dict del snips[snip_name] self.modified.append( (TYPE_GROUP, pkg['path'], snips_fn, snip_name)) self._fill_forms(sel_pkg_path=pkg['path'], sel_group=snips_fn)
def get_url(url, fn, del_first=False): fn_temp = fn + '.download' if os.path.isfile(fn_temp): os.remove(fn_temp) if del_first and os.path.isfile(fn): os.remove(fn) if opt.proxy: proxies = { 'http': opt.proxy, 'https': opt.proxy, } else: proxies = None #print('proxy', proxies) while True: try: r = requests.get(url, proxies=proxies, stream=True) with open(fn_temp, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) #f.flush() commented by recommendation if os.path.isfile(fn_temp): if os.path.isfile(fn): os.remove(fn) os.rename(fn_temp, fn) return except Exception as e: res = app.msg_box( _('Cannot download:\n{}\n{}\n\nRetry?').format(url, str(e)), app.MB_ABORTRETRYIGNORE + app.MB_ICONWARNING) if res == app.ID_IGNORE: return if res == app.ID_ABORT: return False if res == app.ID_CANCEL: return False
def set_files(self, *files): for f in files: for h in ct.ed_handles(): e = ct.Editor(h) file_name = e.get_filename() if file_name == f: if e.get_prop(ct.PROP_MODIFIED): text = 'First you must save file:\n' + \ file_name + \ '\nYES: save and continue\n' + \ "NO: don't save (changes will be lost)" mb = ct.msg_box(text, ct.MB_YESNOCANCEL + ct.MB_ICONQUESTION) if mb == ct.ID_YES: e.save(file_name) elif mb == ct.ID_NO: e.set_prop(ct.PROP_MODIFIED, False) else: return e.focus() e.cmd(ct_cmd.cmd_FileClose) ct.app_idle(True) # better close file sleep(0.3) ct.app_idle(True) # better close file break ct.file_open(files, options='/nohistory') # if file was in group-2, and now group-2 is empty, set "one group" mode if ct.app_proc(ct.PROC_GET_GROUPING, '') in [ct.GROUPS_2VERT, ct.GROUPS_2HORZ]: e = ct.ed_group(1) # Editor obj in group-2 if not e: ct.app_proc(ct.PROC_SET_GROUPING, ct.GROUPS_ONE) self.refresh()
def prepare_vs_snips(f): if not zipfile.is_zipfile(f): ct.msg_box(_("Can't install this package"), ct.MB_OK + ct.MB_ICONERROR) return with zipfile.ZipFile(f) as _zip: with _zip.open('extension/package.json') as package: _f = package.read().decode('utf8') js = json.loads(_f) vs = { 'ext': f, 'name': js.get('name'), 'version': js.get('version'), 'display_name': js.get('displayName'), 'description': js.get('description'), 'links': { 'bugs': get_2keys(js, 'bugs', 'url'), 'repository': get_2keys(js, 'repository', 'url'), 'homepage': js.get('homepage', ''), }, } contributes = js.get('contributes') if not contributes: ct.msg_box( _("Sorry, but this package doesn't have any snippets"), ct.MB_OK + ct.MB_ICONERROR) return files = {} snips = contributes.get('snippets') if not snips: ct.msg_box( _("Sorry, but this package doesn't have any snippets"), ct.MB_OK + ct.MB_ICONERROR) return for sn in snips: lang = sn['language'] path = sn['path'] if path.find('.') == 0: path = path.replace('.', 'extension', 1) paths = files.get(lang, []) paths.append(path) files[lang] = paths vs['files'] = files return vs
def dlg_config(self): ''' Show dlg for change macros list. ''' if app.app_api_version() < FROM_API_VERSION: return app.msg_status('Need update CudaText') keys_json = app.app_path(app.APP_DIR_SETTINGS) + os.sep + 'keys.json' keys = apx._json_loads( open(keys_json).read()) if os.path.exists(keys_json) else {} GAP = 5 ids = [mcr['id'] for mcr in self.macros] mcr_ind = ids.index( self.last_mcr_id) if self.last_mcr_id in ids else -1 pass LOG and log('self.last_mcr_id, mcr_ind={}', (self.last_mcr_id, mcr_ind)) times = 1 waits = 5 chngs = '0' endln = '0' while True: (WD_LST, HT_LST) = (self.dlg_prs.get('w_list', 300), self.dlg_prs.get('h_list', 500)) (WD_ACTS, HT_ACTS) = (self.dlg_prs.get('w_acts', 300), self.dlg_prs.get('h_acts', 500)) (WD_BTN, HT_BTN) = (self.dlg_prs.get('w_btn', 150), 24) l_btn = GAP + WD_LST + GAP vw_acts = (WD_ACTS > 0) WD_ACTS = max(0, WD_ACTS) rec_on = ed.get_prop(app.PROP_MACRO_REC) lmcrs = len(self.macros) pass LOG and log('mcr_ind,vw_acts,rec_on={}', (mcr_ind, vw_acts, rec_on)) nmkys = [] for mcr in self.macros: mcr_cid = 'cuda_macros,run,{}'.format(mcr['id']) mcr_keys = keys.get(mcr_cid, {}) kys = '/'.join([ ' * '.join(mcr_keys.get('s1', [])), ' * '.join(mcr_keys.get('s2', [])) ]).strip('/') nmkys += [mcr['nm'] + (' [' + kys + ']' if kys else '')] mcr_acts = '' if vw_acts and mcr_ind in range(lmcrs): mcr = self.macros[mcr_ind] mcr_acts = '\t'.join(['# ' + nmkys[mcr_ind]] + mcr['evl']) ans = app.dlg_custom( 'Macros', GAP + WD_LST + GAP + WD_BTN + GAP + WD_ACTS + GAP, GAP + HT_LST + GAP, '\n'.join([] + [ C1.join([ 'type=listbox', POS_FMT(l=GAP, t=GAP, r=GAP + WD_LST, b=GAP + HT_LST), 'items=' + '\t'.join(nmkys), 'val=' + str(mcr_ind) # start sel , 'en=' + str(0 if rec_on else 1) # enabled ] # i=0 ) ] + ([ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP * 1 + HT_BTN * 0, r=l_btn + WD_BTN, b=0), 'cap=&View actions...', 'props=' + str(0 if rec_on or 0 == lmcrs else 1) # default , 'en=' + str(0 if rec_on or 0 == lmcrs else 1) # enabled ] # i=1 ) ] if vw_acts else []) + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP * 2 + HT_BTN * 1, r=l_btn + WD_BTN, b=0), 'cap=Hot&keys...', 'en=' + str(0 if rec_on or 0 == lmcrs else 1) # enabled ] # i=2 if vw_acts else i=1 ) ] + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP * 3 + HT_BTN * 2, r=l_btn + WD_BTN, b=0), 'cap=Re&name...', 'en=' + str(0 if rec_on or 0 == lmcrs else 1) # enabled ] # i=3 if vw_acts else i=2 ) ] + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP * 4 + HT_BTN * 3, r=l_btn + WD_BTN, b=0), 'cap=&Delete...', 'en=' + str(0 if rec_on or 0 == lmcrs else 1) # enabled ] # i=4 if vw_acts else i=3 ) ] + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP * 6 + HT_BTN * 5, r=l_btn + WD_BTN, b=0), 'cap=&Run!', 'props=' + str(1 if not vw_acts and not rec_on else 0) # default , 'en=' + str(0 if rec_on or 0 == lmcrs else 1) # enabled ] # i=5 if vw_acts else i=4 ) ] + [ C1.join([ 'type=label', POS_FMT(l=l_btn, t=GAP * 7 + HT_BTN * 6 + 3, r=l_btn + int(WD_BTN / 3), b=0), 'cap=&Times' ] # i=6 if vw_acts else i=5 ) ] + [ C1.join([ 'type=spinedit', POS_FMT(l=l_btn + int(WD_BTN / 3) + GAP, t=GAP * 7 + HT_BTN * 6, r=l_btn + WD_BTN, b=0), 'val=' + str(times), 'props=0,{},1'.format(self.dlg_prs.get('times', 1000)), 'en=' + str(0 if rec_on else 1) # enabled ] # i=7 if vw_acts else i=6 ) ] + [ C1.join([ 'type=label', POS_FMT(l=l_btn, t=GAP * 8 + HT_BTN * 7 + 3, r=l_btn + int(WD_BTN / 3), b=0), 'cap=&Wait' ] # i=8 if vw_acts else i=7 ) ] + [ C1.join([ 'type=spinedit', POS_FMT(l=l_btn + int(WD_BTN / 3) + GAP, t=GAP * 8 + HT_BTN * 7, r=l_btn + WD_BTN - 40, b=0), 'val=' + str(waits), 'props=1,3600,1', 'en=' + str(0 if rec_on else 1) # enabled ] # i=9 if vw_acts else i=8 ) ] + [ C1.join([ 'type=label', POS_FMT(l=l_btn + WD_BTN - 40 + GAP, t=GAP * 8 + HT_BTN * 7 + 3, r=l_btn + WD_BTN, b=0), 'cap=sec' ] # i=10 if vw_acts else i=9 ) ] + [ C1.join([ 'type=check', POS_FMT(l=l_btn, t=GAP * 9 + HT_BTN * 8, r=l_btn + WD_BTN, b=0), 'cap=While text c&hanges', 'val=' + chngs ] # i=11 if vw_acts else i=10 ) ] + [ C1.join([ 'type=check', POS_FMT(l=l_btn, t=GAP * 10 + HT_BTN * 9, r=l_btn + WD_BTN, b=0), 'cap=Until c&aret on last line', 'val=' + endln ] # i=12 if vw_acts else i=11 ) ] + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP * 12 + HT_BTN * 11, r=l_btn + WD_BTN, b=0), 'cap={}'.format( '&Stop record' if rec_on else '&Start record'), 'props=' + str(1 if rec_on or 0 == lmcrs else 0) # default ] # i=13 if vw_acts else i=12 ) ] + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP * 13 + HT_BTN * 12, r=l_btn + WD_BTN, b=0), 'cap=Canc&el record', 'en=' + str(1 if rec_on else 0) # enabled ] # i=14 if vw_acts else i=13 ) ] + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=HT_LST - HT_BTN * 2, r=l_btn + WD_BTN, b=0), 'cap=C&ustom...', 'en=' + str(0 if rec_on else 1) # enabled ] # i=15 if vw_acts else i=14 ) ] + [ C1.join([ 'type=button', POS_FMT(l=l_btn, t=GAP + HT_LST - HT_BTN * 1, r=l_btn + WD_BTN, b=0), 'cap=&Close' ] # i=16 if vw_acts else i=15 ) ] + ([ C1.join([ 'type=memo', POS_FMT(l=GAP + WD_LST + GAP + WD_BTN + GAP, t=GAP, r=GAP + WD_LST + GAP + WD_BTN + GAP + WD_ACTS, b=GAP + HT_ACTS), 'val=' + mcr_acts, 'props=1,1,1' # ro,mono,border ] # i=17 ) ] if vw_acts else [])), apx.icase( vw_acts and not rec_on, 0 # View , not vw_acts and not rec_on, 0 # View , vw_acts and rec_on, 11, not vw_acts and rec_on, 10)) # start focus pass LOG and log('ans={}', ans) if ans is None: break #while (ans_i, vals) = ans ans_s = apx.icase( False, '', vw_acts and ans_i == 1, 'view', vw_acts and ans_i == 2, 'hotkeys', not vw_acts and ans_i == 1, 'hotkeys', vw_acts and ans_i == 3, 'rename', not vw_acts and ans_i == 2, 'rename', vw_acts and ans_i == 4, 'delete', not vw_acts and ans_i == 3, 'delete', vw_acts and ans_i == 5, 'run', not vw_acts and ans_i == 4, 'run', vw_acts and ans_i == 12, 'rec', not vw_acts and ans_i == 7, 'rec', vw_acts and ans_i == 14, 'cancel', not vw_acts and ans_i == 13, 'cancel', vw_acts and ans_i == 15, 'custom', not vw_acts and ans_i == 14, 'custom', vw_acts and ans_i == 16, 'close', not vw_acts and ans_i == 15, 'close', '?') mcr_ind = int(vals.splitlines()[0]) times = int(vals.splitlines()[7 if vw_acts else 6]) waits = int(vals.splitlines()[9 if vw_acts else 8]) chngs = vals.splitlines()[11 if vw_acts else 10] endln = vals.splitlines()[12 if vw_acts else 11] pass LOG and log('mcr_ind,times,waits,chngs,endln={}', (mcr_ind, times, waits, chngs, endln)) if 0 != lmcrs and mcr_ind in range(lmcrs): mcr = self.macros[mcr_ind] self.last_mcr_id = mcr['id'] if ans_s == 'close': break #while if ans_s == 'custom': #Custom custs = app.dlg_input_ex( 5, 'Custom dialog Macros', 'Height of macro list (min 450)', str(self.dlg_prs.get('h_list', 400)), 'Width of macro list (min 200)', str(self.dlg_prs.get('w_list', 500)), 'Width of action list (min 200, <=0-hide)', str(self.dlg_prs.get('w_acts', 500)), 'Width of buttons (min 150)', str(self.dlg_prs.get('w_btn', 150)), 'Max run times (min 100)', str(self.dlg_prs.get('times', 1000))) if custs is not None: self.dlg_prs['h_list'] = max(450, int(custs[0])) self.dlg_prs['h_acts'] = self.dlg_prs['h_list'] self.dlg_prs['w_list'] = max(200, int(custs[1])) self.dlg_prs['w_acts'] = max(200, int( custs[2])) if int(custs[2]) > 0 else int(custs[2]) self.dlg_prs['w_btn'] = max(150, int(custs[3])) self.dlg_prs['times'] = max(100, int(custs[4])) open(MACROS_JSON, 'w').write( json.dumps( { 'ver': JSON_FORMAT_VER, 'list': self.macros, 'dlg_prs': self.dlg_prs }, indent=4)) continue #while if mcr_ind not in range(lmcrs): app.msg_box('Select macro', app.MB_OK) continue #while what = '' changed = False if False: pass elif ans_s == 'view': #View continue #while elif ans_s == 'rename': #Rename mcr_nm = app.dlg_input( 'New name for: {}'.format(nmkys[mcr_ind]), mcr['nm']) if mcr_nm is None or mcr_nm == mcr['nm']: continue #while while mcr_nm in [mcr['nm'] for mcr in self.macros]: app.msg_box( 'Select other name.\nMacro names now are:\n\n' + '\n'.join(nmkys), app.MB_OK) mcr_nm = app.dlg_input( 'New name for: {}'.format(nmkys[mcr_ind]), mcr_nm) if mcr_nm is None or mcr_nm == mcr['nm']: break #while mcr_nm if mcr_nm is None or mcr_nm == mcr['nm']: continue #while what = 'rename' mcr['nm'] = mcr_nm changed = True elif ans_s == 'delete': #Del if app.msg_box('Delete macro\n {}'.format(nmkys[mcr_ind]), app.MB_YESNO) != app.ID_YES: continue #while what = 'delete:' + str(mcr['id']) del self.macros[mcr_ind] mcr_ind = min(mcr_ind, len(self.macros) - 1) changed = True elif ans_s == 'hotkeys': #Hotkeys app.dlg_hotkeys('cuda_macros,run,' + str(mcr['id'])) keys = apx._json_loads(open( keys_json).read()) if os.path.exists(keys_json) else {} changed = True elif ans_s == 'run': #Run if (times == 0 and waits == 0 and chngs == '0' and endln == '0'): app.msg_box('Select stop condition', app.MB_OK) continue self.run(mcr['id'], max(0, times), max(0, waits), chngs == '1', endln == '1') return elif ans_s == 'rec' and not rec_on: #Start record return ed.cmd(cmds.cmd_MacroStart) elif ans_s == 'rec' and rec_on: #Stop record self.need_dlg = True return ed.cmd( cmds.cmd_MacroStop ) # Return for clear rec-mode in StatusBar, will recall from on_macro elif ans_s == 'cancel' and rec_on: #Cancel record return ed.cmd(cmds.cmd_MacroCancel ) # Return for clear rec-mode in StatusBar if changed: self._do_acts(what)
def refresh(self): if ct.ed.get_prop(ct.PROP_EDITORS_LINKED): return a_ed = ct.Editor(ct.ed.get_prop(ct.PROP_HANDLE_PRIMARY)) b_ed = ct.Editor(ct.ed.get_prop(ct.PROP_HANDLE_SECONDARY)) a_file, b_file = a_ed.get_filename(), b_ed.get_filename() if a_file == b_file: return a_text_all = a_ed.get_text_all() b_text_all = b_ed.get_text_all() if a_text_all == '': t = 'The file:\n{}\nis empty.'.format(a_file) ct.msg_box(t, ct.MB_OK) return if b_text_all == '': t = 'The file:\n{}\nis empty.'.format(b_file) ct.msg_box(t, ct.MB_OK) return if a_text_all == b_text_all: t = 'The files are identical:\n{0}\n{1}'.format(a_file, b_file) ct.msg_box(t, ct.MB_OK) return a_ed.set_prop(ct.PROP_WRAP, ct.WRAP_OFF) b_ed.set_prop(ct.PROP_WRAP, ct.WRAP_OFF) self.clear(a_ed) self.clear(b_ed) self.config() self.diff.set_seqs(a_text_all.splitlines(True), b_text_all.splitlines(True)) self.scroll.tab_id.add(ct.ed.get_prop(ct.PROP_TAB_ID)) self.scroll.toggle(self.cfg.get('sync_scroll')) self.diff.withdetail = self.cfg.get('compare_with_details') self.diff.ratio = self.cfg.get('ratio') for d in self.diff.compare(): diff_id, y = d[0], d[1] if diff_id == df.A_LINE_DEL: self.set_bookmark2(a_ed, y, NKIND_DELETED) self.set_decor(a_ed, y, DECOR_CHAR, self.cfg.get('color_deleted')) elif diff_id == df.B_LINE_ADD: self.set_bookmark2(b_ed, y, NKIND_ADDED) self.set_decor(b_ed, y, DECOR_CHAR, self.cfg.get('color_added')) elif diff_id == df.A_LINE_CHANGE: self.set_bookmark2(a_ed, y, NKIND_CHANGED) elif diff_id == df.B_LINE_CHANGE: self.set_bookmark2(b_ed, y, NKIND_CHANGED) elif diff_id == df.A_GAP: self.set_gap(a_ed, y, d[2]) elif diff_id == df.B_GAP: self.set_gap(b_ed, y, d[2]) elif diff_id == df.A_SYMBOL_DEL: self.set_attr(a_ed, d[2], y, d[3], self.cfg.get('color_deleted')) elif diff_id == df.B_SYMBOL_ADD: self.set_attr(b_ed, d[2], y, d[3], self.cfg.get('color_added')) elif diff_id == df.A_DECOR_YELLOW: self.set_decor(a_ed, y, DECOR_CHAR, self.cfg.get('color_changed')) elif diff_id == df.B_DECOR_YELLOW: self.set_decor(b_ed, y, DECOR_CHAR, self.cfg.get('color_changed')) elif diff_id == df.A_DECOR_RED: self.set_decor(a_ed, y, DECOR_CHAR, self.cfg.get('color_deleted')) elif diff_id == df.B_DECOR_GREEN: self.set_decor(b_ed, y, DECOR_CHAR, self.cfg.get('color_added'))
def msg_warn_func(s): app.msg_box(s, app.MB_OK + app.MB_ICONWARNING)
def msg_error_func(s): app.msg_box(s, app.MB_OK + app.MB_ICONERROR)
# # Adapted to CudaLint by Alexey Torgashin, 2020 # # License: MIT # """This module exports the Scalastyle plugin class.""" import os from cuda_lint import Linter, util import cudatext as app import shutil jar_file = app.ini_read('plugins.ini', 'lint_scalastyle', 'jar', '_') if not os.path.isfile(jar_file): app.msg_box( 'Cannot find Scalastyle, see\n settings/plugins.ini\n [lint_scalastyle]\n jar=...', app.MB_OK + app.MB_ICONERROR) cfg_file_init = os.path.join(os.path.dirname(__file__), 'scalastyle_config.xml') cfg_file = os.path.join(app.app_path(app.APP_DIR_SETTINGS), 'scalastyle_config.xml') if not os.path.isfile(cfg_file) and os.path.isfile(cfg_file_init): shutil.copy(cfg_file_init, cfg_file) class Scalastyle(Linter): """Provides an interface to scalastyle.""" syntax = 'Scala'
def dlg_import(self): ''' Show dlg for import some macros. ''' if app.app_api_version() < FROM_API_VERSION: return app.msg_status('Need update CudaText') (imp_file, mcrs) = self.dlg_import_choose_mcrs() if imp_file is None: return lmcrs = len(mcrs) GAP = 5 (WD_LST, HT_LST) = (500, 500) crt, sels = '0', ['1'] * lmcrs while True: ans = app.dlg_custom( 'Import macros', GAP + WD_LST + GAP, GAP * 5 + HT_LST + 25 * 2, '\n'.join([] + [ C1.join([ 'type=label', POS_FMT(l=GAP, t=GAP + 3, r=GAP + 85, b=0), 'cap=Import &from' ] # i=0 ) ] + [ C1.join([ 'type=edit', POS_FMT(l=GAP + 85, t=GAP, r=GAP + WD_LST - 35, b=0), 'val={}'.format(imp_file) ] # i=1 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP + HT_LST - 35, t=GAP - 2, r=GAP + WD_LST, b=0), 'cap=&...' ] # i=2 ) ] + [ C1.join([ 'type=checklistbox', POS_FMT(l=GAP, t=GAP * 2 + 30, r=GAP + WD_LST, b=GAP + 25 + HT_LST), 'items=' + '\t'.join([mcr['nm'] for mcr in mcrs]), 'val=' + crt + ';' + ','.join(sels) ] # i=3 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP * 1, t=GAP * 3 + 25 + HT_LST, r=GAP * 1 + 80 * 1, b=0), 'cap=Check &all' ] # i=4 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP * 2 + 80, t=GAP * 3 + 25 + HT_LST, r=GAP * 2 + 80 * 2, b=0), 'cap=U&ncheck all' ] # i=5 ) ] + [ C1.join([ 'type=button', POS_FMT(l=WD_LST - 60 * 2, t=GAP * 3 + 25 + HT_LST, r=WD_LST - 60 * 1, b=0), 'cap=&Import' ] # i=6 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP + WD_LST - 60 * 1, t=GAP * 3 + 25 + HT_LST, r=GAP + WD_LST - 60 * 0, b=0), 'cap=&Close' ] # i=7 ) ]), 3) # start focus pass LOG and log('ans={}', ans) if ans is None: break #while (ans_i, vals) = ans ans_s = apx.icase(False, '', ans_i == 2, 'file', ans_i == 4, 'all', ans_i == 5, 'no', ans_i == 6, 'imp', ans_i == 7, 'close') if ans_s == 'close': break #while v_3 = vals.splitlines()[3] crt, sels = v_3.split(';') sels = sels.strip(',').split(',') pass LOG and log('sels={}', sels) if False: pass elif ans_s == 'file': (new_imp_file, new_mcrs) = self.dlg_import_choose_mcrs() if new_imp_file is None: continue #while imp_file = new_imp_file mcrs = new_mcrs lmcrs = len(mcrs) crt, sels = '0', ['1'] * lmcrs elif ans_s == 'all': sels = ['1'] * lmcrs elif ans_s == 'no': sels = ['0'] * lmcrs elif ans_s == 'imp': if '1' not in sels: app.msg_box('Select some names', app.MB_OK) continue (good_nms, fail_nms) = self.import_from_list([ mcr for (ind, mcr) in enumerate(mcrs) if sels[ind] == '1' ]) l, lt = '\n', '\n ' app.msg_box( 'Import macros:' + lt + lt.join(good_nms) + l + '' + l + 'Skip duplicates:' + lt + lt.join(fail_nms), app.MB_OK)
def dlg_import(self): ''' Show dlg for import some macros. ''' if app.app_api_version()<FROM_API_VERSION: return app.msg_status('Need update CudaText') (imp_file ,mcrs) = self.dlg_import_choose_mcrs() if imp_file is None: return lmcrs = len(mcrs) GAP = 5 (WD_LST ,HT_LST)= (500 ,500) crt,sels= '0', ['1'] * lmcrs while True: ans = app.dlg_custom('Import macros' ,GAP+WD_LST+GAP, GAP*5+HT_LST+25*2, '\n'.join([] +[C1.join(['type=label' ,POS_FMT(l=GAP, t=GAP+3, r=GAP+85, b=0) ,'cap=Import &from' ] # i=0 )] +[C1.join(['type=edit' ,POS_FMT(l=GAP+85, t=GAP, r=GAP+WD_LST-35,b=0) ,'val={}'.format(imp_file) ] # i=1 )] +[C1.join(['type=button' ,POS_FMT(l=GAP+HT_LST-35, t=GAP-2, r=GAP+WD_LST, b=0) ,'cap=&...' ] # i=2 )] +[C1.join(['type=checklistbox' ,POS_FMT(l=GAP, t=GAP*2+30, r=GAP+WD_LST, b=GAP+25+HT_LST) ,'items=' +'\t'.join([mcr['nm'] for mcr in mcrs]) ,'val=' + crt+';'+','.join(sels) ] # i=3 )] +[C1.join(['type=button' ,POS_FMT(l=GAP*1, t=GAP*3+25+HT_LST, r=GAP*1+80*1, b=0) ,'cap=Check &all' ] # i=4 )] +[C1.join(['type=button' ,POS_FMT(l=GAP*2+80, t=GAP*3+25+HT_LST, r=GAP*2+80*2, b=0) ,'cap=U&ncheck all' ] # i=5 )] +[C1.join(['type=button' ,POS_FMT(l= WD_LST-60*2, t=GAP*3+25+HT_LST, r= WD_LST-60*1, b=0) ,'cap=&Import' ] # i=6 )] +[C1.join(['type=button' ,POS_FMT(l=GAP+WD_LST-60*1, t=GAP*3+25+HT_LST, r=GAP+WD_LST-60*0, b=0) ,'cap=&Close' ] # i=7 )] ), 3) # start focus pass; LOG and log('ans={}',ans) if ans is None: break #while (ans_i ,vals) = ans ans_s = apx.icase(False,'' ,ans_i==2, 'file' ,ans_i==4, 'all' ,ans_i==5, 'no' ,ans_i==6, 'imp' ,ans_i==7, 'close' ) if ans_s=='close': break #while v_3 = vals.splitlines()[3] crt,sels= v_3.split(';') sels = sels.strip(',').split(',') pass; LOG and log('sels={}',sels) if False:pass elif ans_s=='file': (new_imp_file ,new_mcrs) = self.dlg_import_choose_mcrs() if new_imp_file is None: continue #while imp_file = new_imp_file mcrs = new_mcrs lmcrs = len(mcrs) crt,sels = '0', ['1'] * lmcrs elif ans_s=='all': sels = ['1'] * lmcrs elif ans_s=='no': sels = ['0'] * lmcrs elif ans_s=='imp': if '1' not in sels: app.msg_box('Select some names', app.MB_OK) continue (good_nms ,fail_nms) = self.import_from_list([mcr for (ind, mcr) in enumerate(mcrs) if sels[ind]=='1']) l,lt = '\n', '\n ' app.msg_box( 'Import macros:' +lt+lt.join(good_nms) +l+'' +l+'Skip duplicates:' +lt+lt.join(fail_nms) ,app.MB_OK)
import os from cuda_fmt import get_config_filename import cudatext as app if os.name == 'nt': from . import pyastyle else: try: import pyastyle except: pyastyle = None app.msg_box( 'For "AStyle Format", you need to install "pyastyle" Python module in OS. Run:\nsudo pip3 install pyastyle', app.MB_OK + app.MB_ICONERROR) def options(): ini = get_config_filename('AStyle Format') if os.path.isfile(ini): s = open(ini).read() else: s = '' return s def do_format(text): if pyastyle is None: return opt = options() #print('AStyle options:', opt) return pyastyle.format(text, opt)
def dlg_config(self): ''' Show dlg for change macros list. ''' if app.app_api_version()<FROM_API_VERSION: return app.msg_status('Need update CudaText') keys_json = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'keys.json' keys = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {} GAP = 5 ids = [mcr['id'] for mcr in self.macros] mcr_ind = ids.index(self.last_mcr_id) if self.last_mcr_id in ids else -1 pass; LOG and log('self.last_mcr_id, mcr_ind={}',(self.last_mcr_id,mcr_ind)) times = 1 waits = 5 chngs = '0' endln = '0' while True: (WD_LST ,HT_LST)= (self.dlg_prs.get('w_list', 300) ,self.dlg_prs.get('h_list', 500)) (WD_ACTS ,HT_ACTS)=(self.dlg_prs.get('w_acts', 300) ,self.dlg_prs.get('h_acts', 500)) (WD_BTN ,HT_BTN)= (self.dlg_prs.get('w_btn', 150), 24) l_btn = GAP+WD_LST+GAP vw_acts = (WD_ACTS>0) WD_ACTS = max(0, WD_ACTS) rec_on = ed.get_prop(app.PROP_MACRO_REC) lmcrs = len(self.macros) pass; LOG and log('mcr_ind,vw_acts,rec_on={}',(mcr_ind,vw_acts,rec_on)) nmkys = [] for mcr in self.macros: mcr_cid = 'cuda_macros,run,{}'.format(mcr['id']) mcr_keys= keys.get(mcr_cid, {}) kys = '/'.join([' * '.join(mcr_keys.get('s1', [])) ,' * '.join(mcr_keys.get('s2', [])) ]).strip('/') nmkys += [mcr['nm'] + (' ['+kys+']' if kys else '')] mcr_acts= '' if vw_acts and mcr_ind in range(lmcrs): mcr = self.macros[mcr_ind] mcr_acts= '\t'.join(['# '+nmkys[mcr_ind]] + mcr['evl']) ans = app.dlg_custom('Macros' ,GAP+WD_LST+GAP+WD_BTN+GAP+WD_ACTS+GAP,GAP+HT_LST+GAP, '\n'.join([] +[C1.join(['type=listbox' ,POS_FMT(l=GAP, t=GAP, r=GAP+WD_LST, b=GAP+HT_LST) ,'items=' +'\t'.join(nmkys) ,'val=' +str(mcr_ind) # start sel ,'en=' +str(0 if rec_on else 1) # enabled ] # i=0 )] +([C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP*1+HT_BTN*0, r=l_btn+WD_BTN, b=0) ,'cap=&View actions...' ,'props=' +str(0 if rec_on or 0==lmcrs else 1) # default ,'en=' +str(0 if rec_on or 0==lmcrs else 1) # enabled ] # i=1 )] if vw_acts else []) +[C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP*2+HT_BTN*1, r=l_btn+WD_BTN, b=0) ,'cap=Hot&keys...' ,'en=' +str(0 if rec_on or 0==lmcrs else 1) # enabled ] # i=2 if vw_acts else i=1 )] +[C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP*3+HT_BTN*2, r=l_btn+WD_BTN, b=0) ,'cap=Re&name...' ,'en=' +str(0 if rec_on or 0==lmcrs else 1) # enabled ] # i=3 if vw_acts else i=2 )] +[C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP*4+HT_BTN*3, r=l_btn+WD_BTN, b=0) ,'cap=&Delete...' ,'en=' +str(0 if rec_on or 0==lmcrs else 1) # enabled ] # i=4 if vw_acts else i=3 )] +[C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP*6+HT_BTN*5, r=l_btn+WD_BTN, b=0) ,'cap=&Run!' ,'props=' +str(1 if not vw_acts and not rec_on else 0) # default ,'en=' +str(0 if rec_on or 0==lmcrs else 1) # enabled ] # i=5 if vw_acts else i=4 )] +[C1.join(['type=label' ,POS_FMT(l=l_btn, t=GAP*7+HT_BTN*6+3, r=l_btn+int(WD_BTN/3),b=0) ,'cap=&Times' ] # i=6 if vw_acts else i=5 )] +[C1.join(['type=spinedit' ,POS_FMT(l=l_btn+int(WD_BTN/3)+GAP, t=GAP*7+HT_BTN*6, r=l_btn+WD_BTN, b=0) ,'val=' +str(times) ,'props=0,{},1'.format(self.dlg_prs.get('times', 1000)) ,'en=' +str(0 if rec_on else 1) # enabled ] # i=7 if vw_acts else i=6 )] +[C1.join(['type=label' ,POS_FMT(l=l_btn, t=GAP*8+HT_BTN*7+3, r=l_btn+int(WD_BTN/3),b=0) ,'cap=&Wait' ] # i=8 if vw_acts else i=7 )] +[C1.join(['type=spinedit' ,POS_FMT(l=l_btn+int(WD_BTN/3)+GAP, t=GAP*8+HT_BTN*7, r=l_btn+WD_BTN-40, b=0) ,'val=' +str(waits) ,'props=1,3600,1' ,'en=' +str(0 if rec_on else 1) # enabled ] # i=9 if vw_acts else i=8 )] +[C1.join(['type=label' ,POS_FMT(l=l_btn+WD_BTN-40+GAP, t=GAP*8+HT_BTN*7+3, r=l_btn+WD_BTN,b=0) ,'cap=sec' ] # i=10 if vw_acts else i=9 )] +[C1.join(['type=check' ,POS_FMT(l=l_btn, t=GAP*9+HT_BTN*8, r=l_btn+WD_BTN,b=0) ,'cap=While text c&hanges' ,'val=' +chngs ] # i=11 if vw_acts else i=10 )] +[C1.join(['type=check' ,POS_FMT(l=l_btn, t=GAP*10+HT_BTN*9, r=l_btn+WD_BTN,b=0) ,'cap=Until c&aret on last line' ,'val=' +endln ] # i=12 if vw_acts else i=11 )] +[C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP*12+HT_BTN*11, r=l_btn+WD_BTN, b=0) ,'cap={}'.format('&Stop record' if rec_on else '&Start record') ,'props=' +str(1 if rec_on or 0==lmcrs else 0) # default ] # i=13 if vw_acts else i=12 )] +[C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP*13+HT_BTN*12, r=l_btn+WD_BTN, b=0) ,'cap=Canc&el record' ,'en=' +str(1 if rec_on else 0) # enabled ] # i=14 if vw_acts else i=13 )] +[C1.join(['type=button' ,POS_FMT(l=l_btn, t= HT_LST-HT_BTN*2, r=l_btn+WD_BTN, b=0) ,'cap=C&ustom...' ,'en=' +str(0 if rec_on else 1) # enabled ] # i=15 if vw_acts else i=14 )] +[C1.join(['type=button' ,POS_FMT(l=l_btn, t=GAP+HT_LST-HT_BTN*1, r=l_btn+WD_BTN, b=0) ,'cap=&Close' ] # i=16 if vw_acts else i=15 )] +([C1.join(['type=memo' ,POS_FMT(l=GAP+WD_LST+GAP+WD_BTN+GAP, t=GAP, r=GAP+WD_LST+GAP+WD_BTN+GAP+WD_ACTS, b=GAP+HT_ACTS) ,'val='+mcr_acts ,'props=1,1,1' # ro,mono,border ] # i=17 )] if vw_acts else []) ), apx.icase( vw_acts and not rec_on, 0 # View ,not vw_acts and not rec_on, 0 # View , vw_acts and rec_on, 11 ,not vw_acts and rec_on, 10 )) # start focus pass; LOG and log('ans={}',ans) if ans is None: break #while (ans_i ,vals) = ans ans_s = apx.icase(False,'' ,vw_acts and ans_i==1, 'view' ,vw_acts and ans_i==2, 'hotkeys' ,not vw_acts and ans_i==1, 'hotkeys' ,vw_acts and ans_i==3, 'rename' ,not vw_acts and ans_i==2, 'rename' ,vw_acts and ans_i==4, 'delete' ,not vw_acts and ans_i==3, 'delete' ,vw_acts and ans_i==5, 'run' ,not vw_acts and ans_i==4, 'run' ,vw_acts and ans_i==12,'rec' ,not vw_acts and ans_i==7, 'rec' ,vw_acts and ans_i==14,'cancel' ,not vw_acts and ans_i==13,'cancel' ,vw_acts and ans_i==15,'custom' ,not vw_acts and ans_i==14,'custom' ,vw_acts and ans_i==16,'close' ,not vw_acts and ans_i==15,'close' ,'?') mcr_ind = int(vals.splitlines()[0]) times = int(vals.splitlines()[ 7 if vw_acts else 6]) waits = int(vals.splitlines()[ 9 if vw_acts else 8]) chngs = vals.splitlines()[11 if vw_acts else 10] endln = vals.splitlines()[12 if vw_acts else 11] pass; LOG and log('mcr_ind,times,waits,chngs,endln={}',(mcr_ind,times,waits,chngs,endln)) if 0!=lmcrs and mcr_ind in range(lmcrs): mcr = self.macros[mcr_ind] self.last_mcr_id = mcr['id'] if ans_s=='close': break #while if ans_s=='custom': #Custom custs = app.dlg_input_ex(5, 'Custom dialog Macros' , 'Height of macro list (min 450)' , str(self.dlg_prs.get('h_list', 400)) , 'Width of macro list (min 200)' , str(self.dlg_prs.get('w_list', 500)) , 'Width of action list (min 200, <=0-hide)', str(self.dlg_prs.get('w_acts', 500)) , 'Width of buttons (min 150)' , str(self.dlg_prs.get('w_btn', 150)) , 'Max run times (min 100)' , str(self.dlg_prs.get('times', 1000)) ) if custs is not None: self.dlg_prs['h_list'] = max(450, int(custs[0])); self.dlg_prs['h_acts'] = self.dlg_prs['h_list'] self.dlg_prs['w_list'] = max(200, int(custs[1])) self.dlg_prs['w_acts'] = max(200, int(custs[2])) if int(custs[2])>0 else int(custs[2]) self.dlg_prs['w_btn'] = max(150, int(custs[3])) self.dlg_prs['times'] = max(100, int(custs[4])) open(MACROS_JSON, 'w').write(json.dumps({'ver':JSON_FORMAT_VER, 'list':self.macros, 'dlg_prs':self.dlg_prs}, indent=4)) continue #while if mcr_ind not in range(lmcrs): app.msg_box('Select macro', app.MB_OK) continue #while what = '' changed = False if False:pass elif ans_s=='view': #View continue #while elif ans_s=='rename': #Rename mcr_nm = app.dlg_input('New name for: {}'.format(nmkys[mcr_ind]) ,mcr['nm']) if mcr_nm is None or mcr_nm==mcr['nm']: continue #while while mcr_nm in [mcr['nm'] for mcr in self.macros]: app.msg_box('Select other name.\nMacro names now are:\n\n'+'\n'.join(nmkys), app.MB_OK) mcr_nm = app.dlg_input('New name for: {}'.format(nmkys[mcr_ind]) ,mcr_nm) if mcr_nm is None or mcr_nm==mcr['nm']: break #while mcr_nm if mcr_nm is None or mcr_nm==mcr['nm']: continue #while what = 'rename' mcr['nm'] = mcr_nm changed = True elif ans_s=='delete': #Del if app.msg_box( 'Delete macro\n {}'.format(nmkys[mcr_ind]) , app.MB_YESNO)!=app.ID_YES: continue #while what = 'delete:'+str(mcr['id']) del self.macros[mcr_ind] mcr_ind = min(mcr_ind, len(self.macros)-1) changed = True elif ans_s=='hotkeys': #Hotkeys app.dlg_hotkeys('cuda_macros,run,'+str(mcr['id'])) keys = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {} changed = True elif ans_s=='run': #Run if (times==0 and waits==0 and chngs=='0' and endln=='0'): app.msg_box('Select stop condition', app.MB_OK) continue self.run(mcr['id'], max(0, times), max(0, waits), chngs=='1', endln=='1') return elif ans_s=='rec' and not rec_on: #Start record return ed.cmd(cmds.cmd_MacroStart) elif ans_s=='rec' and rec_on: #Stop record self.need_dlg = True return ed.cmd(cmds.cmd_MacroStop) # Return for clear rec-mode in StatusBar, will recall from on_macro elif ans_s=='cancel' and rec_on: #Cancel record return ed.cmd(cmds.cmd_MacroCancel) # Return for clear rec-mode in StatusBar if changed: self._do_acts(what)
def run_app(text, config): tab_spaces = app.ed.get_prop(app.PROP_TAB_SPACES) tab_size = app.ed.get_prop(app.PROP_TAB_SIZE) lexer = app.ed.get_prop(app.PROP_LEXER_FILE) syntax = LANGS.get(lexer, 'C') program = PROGRAM if os.name == 'nt': fn = os.path.join(app.app_path(app.APP_DIR_EXE), 'tools', 'uncrustify.exe') if os.path.exists(fn): program = fn command = [ program, '-l', syntax, '-c', config, '--set', 'newlines=LF', '--set', 'indent_with_tabs=' + str(0 if tab_spaces else 1), '--set', 'indent_columns=' + str(tab_size), '--set', 'input_tab_size=' + str(tab_size), '--set', 'output_tab_size=' + str(tab_size), ] print('Running:', ' '.join(command)) content = text.encode("utf-8") try: if os.name == 'nt': # to hide the console window brings from command si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW # si.wShowWindow = subprocess.SW_HIDE # this is default provided proc = subprocess.Popen(command, \ stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, startupinfo = si) else: proc = subprocess.Popen(command, \ stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) outs, errs = proc.communicate(input=content) ret_code = proc.poll() if ret_code != 0: if errs: msg = errs.decode("utf-8") # slice the last useless part if found (from Uncrustify) pos = msg.find("Try running with -h for usage information") err = "Uncrustify failed (0x%X)\n\n%s" % (ret_code, msg[:pos]) else: err = "Uncrustify stopped (0x%X)" % ret_code app.msg_box(err, app.MB_OK + app.MB_ICONWARNING) return except (OSError, ValueError, subprocess.CalledProcessError, Exception) as e: err = "Cannot execute '%s':\n\n%s" % (command[0], e) app.msg_box(err, app.MB_OK + app.MB_ICONERROR) return formatted_code = outs.decode("utf-8") return formatted_code
def dlg_export(self): ''' Show dlg for export some macros. ''' if app.app_api_version() < FROM_API_VERSION: return app.msg_status('Need update CudaText') if 0 == len(self.macros): return app.msg_status('No macros for export') exp_file = app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros') exp_file = '' if exp_file is None else exp_file exp_file = exp_file + ('' if '' == exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros') (WD_LST, HT_LST) = (500, 500) lmcrs = len(self.macros) crt, sels = '0', ['0'] * lmcrs while True: pass LOG and log('sels={}', sels) ans = app.dlg_custom( 'Export macros', GAP + WD_LST + GAP, GAP * 5 + HT_LST + 25 * 2, '\n'.join([] + [ C1.join([ 'type=label', POS_FMT(l=GAP, t=GAP + 3, r=GAP + 70, b=0), 'cap=Export &to' ] # i=0 ) ] + [ C1.join([ 'type=edit', POS_FMT(l=GAP + 70, t=GAP, r=GAP + WD_LST - 35, b=0), 'val={}'.format(exp_file) ] # i=1 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP + HT_LST - 35, t=GAP - 2, r=GAP + WD_LST, b=0), 'cap=&...' ] # i=2 ) ] + [ C1.join([ 'type=checklistbox', POS_FMT(l=GAP, t=GAP * 2 + 30, r=GAP + WD_LST, b=GAP + 25 + HT_LST), 'items=' + '\t'.join([mcr['nm'] for mcr in self.macros]), 'val=' + crt + ';' + ','.join(sels) ] # i=3 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP * 1, t=GAP * 3 + 25 + HT_LST, r=GAP * 1 + 80 * 1, b=0), 'cap=Check &all' ] # i=4 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP * 2 + 80, t=GAP * 3 + 25 + HT_LST, r=GAP * 2 + 80 * 2, b=0), 'cap=U&ncheck all' ] # i=5 ) ] + [ C1.join([ 'type=button', POS_FMT(l=WD_LST - 60 * 2, t=GAP * 3 + 25 + HT_LST, r=WD_LST - 60 * 1, b=0), 'cap=&Export' ] # i=6 ) ] + [ C1.join([ 'type=button', POS_FMT(l=GAP + WD_LST - 60 * 1, t=GAP * 3 + 25 + HT_LST, r=GAP + WD_LST - 60 * 0, b=0), 'cap=&Close' ] # i=7 ) ]), 3) # start focus pass LOG and log('ans={}', ans) if ans is None: break #while (ans_i, vals) = ans ans_s = apx.icase(False, '', ans_i == 2, 'file', ans_i == 4, 'all', ans_i == 5, 'no', ans_i == 6, 'exp', ans_i == 7, 'close') if ans_s == 'close': break #while v_3 = vals.splitlines()[3] crt, sels = v_3.split(';') sels = sels.strip(',').split(',') pass LOG and log('sels={}', sels) if False: pass elif ans_s == 'file': new_exp_file = app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros') if new_exp_file is not None: exp_file = new_exp_file exp_file = exp_file + ('' if '' == exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros') elif ans_s == 'all': sels = ['1'] * lmcrs elif ans_s == 'no': sels = ['0'] * lmcrs elif ans_s == 'exp': if '1' not in sels: app.msg_box('Select some names', app.MB_OK) continue self.export_to_file(exp_file, [ mcr for (ind, mcr) in enumerate(self.macros) if sels[ind] == '1' ]) return
def do_setv(self, aid, ag, data): M,m = self.__class__,self pass; #LOG and log('aid,m.cur_op={}',(aid,m.cur_op)) if not m.cur_op: return [] #m.col_ws= [ci['wd'] for ci in m.ag.cattr('lvls', 'cols')] cur_val = data trg = 'lexer '+m.lexr+'.json' if m.for_ulf=='l' else 'user.join' key4v = m.for_ulf+'val' op = m.cur_op oi = m.opts_full[op] frm = oi['frm'] dval = oi.get( 'def') uval = oi.get('uval') lval = oi.get('lval') fval = oi.get('fval') ulfvl = oi.get(key4v ) #fval if m.for_ulf=='f' else lval if m.for_ulf=='l' else uval jval = oi['jlvl'] if m.for_ulf=='l' else \ oi['juvl'] if m.for_ulf=='u' else \ oi['jfvl'] # Get new value newv = None erpt_s = '' if False:pass elif aid=='setd' and m.for_ulf=='f' and op in apx.OPT2PROP: # Remove from file - set over def/user/lex val newv = oi.get('lval', oi.get('uval', oi.get('def'))) if newv==ulfvl: #m.stbr_act(M.STBR_MSG, _('No need changes')) return [] erpt_s = 'reset-f' m.ed.set_prop(apx.OPT2PROP[op], newv) elif aid=='setd' and ulfvl is not None and m.for_ulf!='f': # Remove from user/lexer newv= None elif aid=='setv': # Add/Set opt for user/lexer/file # Enter from edit. Need parse some string #newv = m.ag.cval('eded') newv = cur_val try: newv = int(newv) if frm=='int' else \ float(newv) if frm=='float' else \ newv except Exception as ex: app.msg_box(f(_('Incorrect value. It\'s needed in format: {}'), frm) , app.MB_OK+app.MB_ICONWARNING) return d(form=d(fid='eded')) if frm=='#rgb' or frm=='#rgb-e' and newv: # Testing new val try: apx.html_color_to_int(newv) except Exception as ex: app.msg_box(f(_('Incorrect value. It\'s needed in format: {}'), '#RGB or #RRGGBB') , app.MB_OK+app.MB_ICONWARNING) return d(form=d(fid='eded')) ### Use new value to change env if newv is not None and newv==ulfvl: #m.stbr_act(M.STBR_MSG, _('No need changes')) return [] if m.for_ulf=='f' and newv is not None and op in apx.OPT2PROP: # Change for file erpt_s = 'set-f' ed.set_prop(apx.OPT2PROP[op], newv) if m.for_ulf!='f': # Change target file pass; #LOG and log('?? do_erpt',()) erpt_s =('reset-u' if newv is None and m.for_ulf=='u' else 'reset-l' if newv is None and m.for_ulf=='l' else 'add-u' if ulfvl is None and m.for_ulf=='u' else 'add-l' if ulfvl is None and m.for_ulf=='l' else 'set-u' if m.for_ulf=='u' else 'set-l' if m.for_ulf=='l' else '') pass; #LOG and log('?? set_opt',()) apx.set_opt(op ,newv ,apx.CONFIG_LEV_LEX if m.for_ulf=='l' else apx.CONFIG_LEV_USER ,ed_cfg =None ,lexer =m.lexr if m.for_ulf=='l' else None ,user_json=m.how.get('stor_json', 'user.json') ) if not m.apply_one: pass; #LOG and log('?? OpsReloadAndApply',()) ed.cmd(cmds.cmd_OpsReloadAndApply) else: m.apply_need = True # Use new value to change dlg data pass; #LOG and log('?? oi={}',(oi)) pass; #LOG and log('?? m.opts_full={}',pf(m.opts_full)) if False:pass elif aid=='setd': oi.pop(key4v, None) if m.for_ulf!='f' else 0 else: pass; #LOG and log('key4v, newv={}',(key4v, newv)) oi[key4v] = newv pass; #LOG and log('oi={}',(oi)) upd_cald_vals(m.opts_full) pass; #LOG and log('oi={}',(oi)) jnewv = oi['jlvl'] if m.for_ulf=='l' else oi['juvl'] if m.for_ulf=='u' else oi['jfvl'] #m.do_erpt(erpt_s, jnewv, jval) pass; #LOG and log('ok oi={}',(oi)) pass; #LOG and log('ok m.opts_full={}',pf(m.opts_full)) pass; #LOG and log('?? get_cnts',()) if m.for_ulf!='f' and m.auto4file and op in apx.OPT2PROP: # Change FILE to over (("over" - override?)) newv = oi.get('lval', oi.get('uval', oi.get('def'))) if newv!=oi.get('fval'): erpt_s = 'reset-f' m.ed.set_prop(apx.OPT2PROP[op], newv) oi['fval'] = newv jval = oi['jfvl'] upd_cald_vals(m.opts_full) jnewv = oi['jfvl'] #m.do_erpt('auset-f', jnewv, jval) pass; #LOG and log('m.get_vals(lvls-cur)={}',(m.get_vals('lvls-cur')))
def do_work(self, aid, ag, data=''): m,M = self,self.__class__ lwks_n = ag.cval('lwks') if lwks_n==-1: return [] #continue#while m.cmd_id = m.fl_Is[lwks_n] if False:pass elif aid in ('del1', 'del2'): # Delete the hotkeys cmd_nkk = m.id2nkks[m.cmd_id] del_i = 1 if aid=='del1' else 2 if not cmd_nkk[del_i]: return [] #continue#while cmd_nkk[del_i] = '' if cmd_nkk[2]: cmd_nkk[1] = cmd_nkk[2] cmd_nkk[2] = '' set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', m.cmd_id, cmd_nkk[1], cmd_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', m.cmd_id) m.nkki_l, \ m.id2nkks, \ m.ks2id = M.prep_keys_info() elif aid in ('add1', 'add2'): ext_k = app.dlg_hotkey() pass; #LOG and log('ext_k={}',(ext_k,)) if ext_k is None: return [] #continue#while cmd_nkk = m.id2nkks[m.cmd_id] add_i = 1 if aid=='add1' else 2 old_k = cmd_nkk[add_i] new_k = old_k + ' * ' + ext_k if old_k else ext_k pass; #LOG and log('cmd_nkk,old_k,new_k={}',(cmd_nkk,old_k,new_k)) if new_k in m.ks2id: dbl_id = m.ks2id[new_k] dbl_nkk = m.id2nkks[dbl_id] if app.msg_box(f(_('Hotkey "{}" is already assigned ' '\nto command "{}".' '\n' '\nDo you want to reassign the hotkey ' '\nto selected command "{}"?') , new_k, dbl_nkk[0], cmd_nkk[0]), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while dbl_i = 1 if dbl_nkk[1]==new_k else 2 pass; #LOG and log('dbl_id, dbl_nkk={}',(dbl_id, dbl_nkk)) dbl_nkk[dbl_i] = '' if dbl_nkk[2]: dbl_nkk[1], dbl_nkk[2] = dbl_nkk[2], '' pass; #LOG and log('dbl_id, dbl_nkk={}',(dbl_id, dbl_nkk)) set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', dbl_id, dbl_nkk[1], dbl_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', dbl_id) cmd_nkk[add_i] = new_k pass; #LOG and log('cmd_id, cmd_nkk={}',(cmd_id, cmd_nkk)) set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', m.cmd_id, cmd_nkk[1], cmd_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', m.cmd_id) m.nkki_l, \ m.id2nkks, \ m.ks2id = M.prep_keys_info() elif aid=='asnp' and sndt: cnm = sndt.get_name(m.cmd_id) new_sn = app.dlg_input(f(_('Add snip for "{}"'), cnm), '') if not new_sn: return [] #continue#while while not SnipData.is_snip(new_sn): app.msg_status(SnipData.msg_correct_snip) new_sn = app.dlg_input(f(_('Snip for "{}"'), cnm), new_sn) if not new_sn: break if not new_sn: return [] #continue#while pre_cid = sndt.get_cmdid(new_sn) if pre_cid: pre_cnm = sndt.get_name(pre_cid) if app.msg_box(f(_('Snippet "{}" is already assigned' '\nto command "{}".' '\n' '\nDo you want to reassign the snippet' '\nto command "{}"?') , new_sn, pre_cnm, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while sndt.set(new_sn, cmd_id) elif aid=='rsnp' and sndt: cnm = sndt.get_name(m.cmd_id) snp_l = sndt.get_snips(m.cmd_id) snps = ', '.join(snp_l) if app.msg_box(f(_('Do you want to remove snip(s) ' '\n {}' '\nfor command "{}"?') , snps, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while for snp in snp_l: sndt.free(snp) return dict(ctrls=self.get_cnts('lwks') , vals =self.get_vals('lwks') , fid ='lwks' )
import string as _string import cudatext as _ct if _ct.app_api_version() < '1.0.114': _ct.msg_box('Hilite Occurrences needs newer app version', _ct.MB_OK + _ct.MB_ICONWARNING) #----------------------Settings---------------------# MIN_LEN = 1 # For word or selected text. MAX_SIZE = 0 # In bytes. Not used yet. CHARS = _string.ascii_letters + _string.digits + '_' SEL_ALLOW = True # Hilite all occurrences of selected text. SEL_ALLOW_WHITE_SPACE = False # Hilite spaces there located in begin or end of selection SEL_CASE_SENSITIVE = False SEL_WORDS_ONLY = False # Hilite character only if it containts in CHARS. SEL_WHOLE_WORDS = False # Whole word only. Used only if bool(SEL_WORDS_ONLY) == True. CARET_ALLOW = True # Hilite all occurrences of word under caret. CARET_CASE_SENSITIVE = True CARET_WHOLE_WORDS = True # Whole word only. COLOR_FONT_OTHER = 0x000000 COLOR_BG_OTHER = 0x80FFFF COLOR_FONT_CURRENT = COLOR_FONT_OTHER COLOR_BG_CURRENT = 0xe3c1e3 #-----------------------------------------------# MARKTAG = 101 #uniq value for all markers plugins class Command:
def dlg_export(self): ''' Show dlg for export some macros. ''' if app.app_api_version()<FROM_API_VERSION: return app.msg_status('Need update CudaText') if 0==len(self.macros): return app.msg_status('No macros for export') exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros') exp_file= '' if exp_file is None else exp_file exp_file= exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros') (WD_LST ,HT_LST)= (500 ,500) lmcrs = len(self.macros) crt,sels= '0', ['0'] * lmcrs while True: pass; LOG and log('sels={}',sels) ans = app.dlg_custom('Export macros' ,GAP+WD_LST+GAP, GAP*5+HT_LST+25*2, '\n'.join([] +[C1.join(['type=label' ,POS_FMT(l=GAP, t=GAP+3, r=GAP+70, b=0) ,'cap=Export &to' ] # i=0 )] +[C1.join(['type=edit' ,POS_FMT(l=GAP+70, t=GAP, r=GAP+WD_LST-35,b=0) ,'val={}'.format(exp_file) ] # i=1 )] +[C1.join(['type=button' ,POS_FMT(l=GAP+HT_LST-35, t=GAP-2, r=GAP+WD_LST, b=0) ,'cap=&...' ] # i=2 )] +[C1.join(['type=checklistbox' ,POS_FMT(l=GAP, t=GAP*2+30, r=GAP+WD_LST, b=GAP+25+HT_LST) ,'items=' +'\t'.join([mcr['nm'] for mcr in self.macros]) ,'val=' + crt+';'+','.join(sels) ] # i=3 )] +[C1.join(['type=button' ,POS_FMT(l=GAP*1, t=GAP*3+25+HT_LST, r=GAP*1+80*1, b=0) ,'cap=Check &all' ] # i=4 )] +[C1.join(['type=button' ,POS_FMT(l=GAP*2+80, t=GAP*3+25+HT_LST, r=GAP*2+80*2, b=0) ,'cap=U&ncheck all' ] # i=5 )] +[C1.join(['type=button' ,POS_FMT(l= WD_LST-60*2, t=GAP*3+25+HT_LST, r= WD_LST-60*1, b=0) ,'cap=&Export' ] # i=6 )] +[C1.join(['type=button' ,POS_FMT(l=GAP+WD_LST-60*1, t=GAP*3+25+HT_LST, r=GAP+WD_LST-60*0, b=0) ,'cap=&Close' ] # i=7 )] ), 3) # start focus pass; LOG and log('ans={}',ans) if ans is None: break #while (ans_i ,vals) = ans ans_s = apx.icase(False,'' ,ans_i==2, 'file' ,ans_i==4, 'all' ,ans_i==5, 'no' ,ans_i==6, 'exp' ,ans_i==7, 'close' ) if ans_s=='close': break #while v_3 = vals.splitlines()[3] crt,sels= v_3.split(';') sels = sels.strip(',').split(',') pass; LOG and log('sels={}',sels) if False:pass elif ans_s=='file': new_exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros') if new_exp_file is not None: exp_file = new_exp_file exp_file = exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros') elif ans_s=='all': sels = ['1'] * lmcrs elif ans_s=='no': sels = ['0'] * lmcrs elif ans_s=='exp': if '1' not in sels: app.msg_box('Select some names', app.MB_OK) continue self.export_to_file(exp_file, [mcr for (ind, mcr) in enumerate(self.macros) if sels[ind]=='1']) return
def dlg_config(self): ''' Show dlg for change macros list. ''' if app.app_api_version()<FROM_API_VERSION: return app.msg_status(_('Need update CudaText')) keys_json = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'keys.json' keys = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {} ids = [mcr['id'] for mcr in self.macros] mcr_ind = ids.index(self.last_mcr_id) if self.last_mcr_id in ids else -1 pass; LOG and log('self.last_mcr_id, mcr_ind={}',(self.last_mcr_id,mcr_ind)) times = 1 waits = 5 chngs = '0' endln = '0' while True: WD_LST, \ HT_LST = (self.dlg_prs.get('w_list', 300) ,self.dlg_prs.get('h_list', 500)) WD_ACTS,\ HT_ACTS = (self.dlg_prs.get('w_acts', 300) ,self.dlg_prs.get('h_acts', 500)) WD_BTN, \ HT_BTN = (self.dlg_prs.get('w_btn', 150), 24) WD_BTN_3= int(WD_BTN/3) l_btn = GAP+WD_LST+GAP l_acts = GAP+WD_LST+GAP+WD_BTN+GAP vw_acts = (WD_ACTS>0) WD_ACTS = max(0, WD_ACTS) rec_on = ed.get_prop(app.PROP_MACRO_REC) lmcrs = len(self.macros) pass; LOG and log('mcr_ind,vw_acts,rec_on={}',(mcr_ind,vw_acts,rec_on)) nmkys = [] for mcr in self.macros: mcr_cid = 'cuda_macros,run,{}'.format(mcr['id']) mcr_keys= keys.get(mcr_cid, {}) kys = '/'.join([' * '.join(mcr_keys.get('s1', [])) ,' * '.join(mcr_keys.get('s2', [])) ]).strip('/') nmkys += [mcr['nm'] + (' ['+kys+']' if kys else '')] mcr_acts= [''] # mcr_acts= '' if vw_acts and mcr_ind in range(lmcrs): mcr = self.macros[mcr_ind] mcr_acts= ['# '+nmkys[mcr_ind]] + mcr['evl'] # mcr_acts= '\t'.join(['# '+nmkys[mcr_ind]] + mcr['evl']) def_stst = '1' if rec_on or 0==lmcrs else '0' n_edable = '0' if rec_on or 0==lmcrs else '1' n_vwable = '1' if not vw_acts and not rec_on else '0' only_rec_off= '0' if rec_on else '1' only_rec_on = '1' if rec_on else '0' tims_props = '0,{},1'.format(self.dlg_prs.get('times', 1000)) stst_cap = _('&Stop record') if rec_on else _('&Start record') cnts = ([] +[dict(cid='mrcs' ,tp='lbx' ,t=GAP ,h=HT_LST ,l=GAP ,w=WD_LST ,items=nmkys ,en=only_rec_off )] +( [dict(cid='view' ,tp='bt' ,t=GAP* 1+HT_BTN* 0 ,l=l_btn ,w=WD_BTN ,cap=_('&View actions') ,props=n_edable,en=n_edable )] # default if vw_acts else []) +[dict(cid='keys' ,tp='bt' ,t=GAP* 2+HT_BTN* 1 ,l=l_btn ,w=WD_BTN ,cap=_('Hot&keys...') ,en=n_edable )] +[dict(cid='renm' ,tp='bt' ,t=GAP* 3+HT_BTN* 2 ,l=l_btn ,w=WD_BTN ,cap=_('Re&name...') ,en=n_edable )] +[dict(cid='del' ,tp='bt' ,t=GAP* 4+HT_BTN* 3 ,l=l_btn ,w=WD_BTN ,cap=_('&Delete...') ,en=n_edable )] +[dict(cid='run' ,tp='bt' ,t=GAP* 6+HT_BTN* 5 ,l=l_btn ,w=WD_BTN ,cap=_('&Run!') ,props=n_vwable ,en=n_edable )] # default +[dict( tp='lb' ,tid='times' ,l=l_btn ,w=WD_BTN_3 ,cap=_('&Times') )] +[dict(cid='times' ,tp='sp-ed',t=GAP* 7+HT_BTN* 6 ,l=l_btn+WD_BTN_3+GAP ,r=l_btn+WD_BTN ,props=tims_props,en=only_rec_off )] # min,max,step +[dict( tp='lb' ,tid='waits' ,l=l_btn ,w=WD_BTN_3 ,cap=_('&Wait') )] +[dict(cid='waits' ,tp='sp-ed',t=GAP* 8+HT_BTN* 7 ,l=l_btn+WD_BTN_3+GAP ,r=l_btn+WD_BTN-40 ,props='1,3600,1',en=only_rec_off )] # min,max,step +[dict( tp='lb' ,tid='waits' ,l=l_btn+WD_BTN-40+GAP ,w=WD_BTN ,cap=_('sec') )] +[dict(cid='chngs' ,tp='ch' ,t=GAP* 9+HT_BTN* 8 ,l=l_btn ,w=WD_BTN ,cap=_('While text c&hanges') )] +[dict(cid='endln' ,tp='ch' ,t=GAP*10+HT_BTN* 9 ,l=l_btn ,w=WD_BTN ,cap=_('Until c&aret on last line') )] +[dict(cid='stst' ,tp='bt' ,t=GAP*12+HT_BTN*11 ,l=l_btn ,w=WD_BTN ,cap=stst_cap ,props=def_stst )] +[dict(cid='canc' ,tp='bt' ,t=GAP*13+HT_BTN*12 ,l=l_btn ,w=WD_BTN ,cap=_('Canc&el record') ,en=only_rec_on )] +[dict(cid='adju' ,tp='bt' ,t= HT_LST-HT_BTN*2 ,l=l_btn ,w=WD_BTN ,cap=_('Ad&just...') ,en=only_rec_off )] +[dict(cid='-' ,tp='bt' ,t=GAP+HT_LST-HT_BTN*1 ,l=l_btn ,w=WD_BTN ,cap=_('Close') )] +( [dict(cid='acts' ,tp='me' ,t=GAP ,h=HT_ACTS ,l=l_acts ,w=WD_ACTS ,props='1,1,1' )] # ro,mono,border if vw_acts else []) ) vals = dict( mrcs=mcr_ind ,times=times ,waits=waits ,chngs=chngs ,endln=endln ) if vw_acts: vals.update( dict( acts=mcr_acts )) btn, \ vals, \ chds = dlg_wrapper(_('Macros'), GAP+WD_LST+GAP+WD_BTN+GAP+WD_ACTS+GAP,GAP+HT_LST+GAP, cnts, vals, focus_cid='mrcs') if btn is None or btn=='-': return mcr_ind = vals['mrcs'] times = vals['times'] waits = vals['waits'] chngs = vals['chngs'] endln = vals['endln'] pass; LOG and log('mcr_ind,times,waits,chngs,endln={}',(mcr_ind,times,waits,chngs,endln)) if 0!=lmcrs and mcr_ind in range(lmcrs): mcr = self.macros[mcr_ind] self.last_mcr_id = mcr['id'] # if ans_s=='close': break #while if btn=='adju': #ans_s=='custom': #Custom custs = app.dlg_input_ex(5, _('Custom dialog Macros') , _('Height of macro list (min 450)') , str(self.dlg_prs.get('h_list', 400)) , _('Width of macro list (min 200)') , str(self.dlg_prs.get('w_list', 500)) , _('Width of action list (min 200, <=0-hide)'), str(self.dlg_prs.get('w_acts', 500)) , _('Width of buttons (min 150)') , str(self.dlg_prs.get('w_btn', 150)) , _('Max run times (min 100)') , str(self.dlg_prs.get('times', 1000)) ) if custs is not None: self.dlg_prs['h_list'] = max(450, int(custs[0])); self.dlg_prs['h_acts'] = self.dlg_prs['h_list'] self.dlg_prs['w_list'] = max(200, int(custs[1])) self.dlg_prs['w_acts'] = max(200, int(custs[2])) if int(custs[2])>0 else int(custs[2]) self.dlg_prs['w_btn'] = max(150, int(custs[3])) self.dlg_prs['times'] = max(100, int(custs[4])) open(MACROS_JSON, 'w').write(json.dumps({'ver':JSON_FORMAT_VER, 'list':self.macros, 'dlg_prs':self.dlg_prs}, indent=4)) continue #while if mcr_ind not in range(lmcrs): app.msg_box(_('Select macro'), app.MB_OK) continue #while what = '' changed = False if False:pass elif btn=='view': #ans_s=='view': #View continue #while elif btn=='renm': #ans_s=='rename': #Rename mcr_nm = app.dlg_input(_('New name for: {}').format(nmkys[mcr_ind]) ,mcr['nm']) if mcr_nm is None or mcr_nm==mcr['nm']: continue #while while mcr_nm in [mcr['nm'] for mcr in self.macros]: app.msg_box(_('Select other name.\nMacro names now are:\n\n')+'\n'.join(nmkys), app.MB_OK) mcr_nm = app.dlg_input(_('New name for: {}').format(nmkys[mcr_ind]) ,mcr_nm) if mcr_nm is None or mcr_nm==mcr['nm']: break #while mcr_nm if mcr_nm is None or mcr_nm==mcr['nm']: continue #while what = 'rename' mcr['nm'] = mcr_nm changed = True elif btn=='del': #ans_s=='delete': #Del if app.msg_box( _('Delete macro\n {}').format(nmkys[mcr_ind]) , app.MB_YESNO)!=app.ID_YES: continue #while what = 'delete:'+str(mcr['id']) del self.macros[mcr_ind] mcr_ind = min(mcr_ind, len(self.macros)-1) changed = True elif btn=='keys': #ans_s=='hotkeys': #Hotkeys app.dlg_hotkeys('cuda_macros,run,'+str(mcr['id'])) keys = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {} changed = True elif btn=='run': #ans_s=='run': #Run if (times==0 and waits==0 and chngs=='0' and endln=='0'): app.msg_box(_('Select stop condition'), app.MB_OK) continue self.run(mcr['id'], max(0, times), max(0, waits), chngs=='1', endln=='1') return elif btn=='stst' and not rec_on: #Start record # elif ans_s=='rec' and not rec_on: #Start record return ed.cmd(cmds.cmd_MacroStart) elif btn=='stst' and rec_on: #Stop record # elif ans_s=='rec' and rec_on: #Stop record self.need_dlg = True return ed.cmd(cmds.cmd_MacroStop) # Return for clear rec-mode in StatusBar, will recall from on_macro elif btn=='canc' and rec_on: #Cancel record # elif ans_s=='cancel' and rec_on: #Cancel record return ed.cmd(cmds.cmd_MacroCancel) # Return for clear rec-mode in StatusBar if changed: self._do_acts(what)
def dlg(self): if app.app_api_version()<'1.0.212': # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN return app.msg_status(_('Need update CudaText')) sndt = self.sndt reND = re.compile(r'\W') def is_cond4name(cond, text): if not cond: return True if '_' in cond: text = '·' + reND.sub('·', text) + '·' cond = ' ' + cond + ' ' cond = cond.replace(' _', ' ·').replace('_ ', '· ') pass; #LOG and log('cond, text={}',(cond, text)) return all(map(lambda cw: cw in text, cond.split())) def is_cond4snps(cond, sns_l): if not cond: return True if not sns_l: return False return any(map(lambda sn:fnmatch(sn, cond), sns_l)) def bmix(val1, bor2, val2): return val1 or val2 if bor2 else val1 and val2 cmds_l = [(cid, sndt.get_name(cid)) for cid in sndt.cmd_ids()] ccnd_h = _('Suitable command names will contain all specified words.' '\r · Case is ignored.' '\r · Use "_" for word boundary.' '\r "_up" selects "upper" but not "group".') scnd_h = _('Suitable command snips will match specified string.' '\r · Case is important.' '\r · Use ? for any character and * for any fragment.') cmd_id = '' ccnd = '' scnd = '' orcn = False focused = 'ccnd' while True: pass; #LOG and log('ccnd, scnd={}',(ccnd, scnd)) cins_l = [ (cid, cnm, sndt.get_snips(cid)) for cid, cnm in cmds_l] fcins_l = [ (cid, cnm, sns) for (cid, cnm, sns) in cins_l if bmix( not ccnd or is_cond4name(ccnd.upper(), cnm.upper()) ,orcn, not scnd or is_cond4snps(scnd, sns) ) ] fi_l = [ cid for (cid, cnm, sn) in fcins_l] stat = f(' ({}/{})',len(fcins_l), len(cmds_l)) itms = (zip([_('Command')+stat, _('Snip(s)')], map(str, [350, 150])) , [ (cnm, ', '.join(sns)) for (cid, cnm, sns) in fcins_l ]) cnts =[dict(cid='fltr',tp='bt' ,tid='scnd' ,l=5+520+5 ,w=110 ,cap=_('&Filter') ,props='1' ) # &f default ,dict(cid='drop',tp='bt' ,t=5+50 ,l=5+520+5 ,w=110 ,cap=_('&All') ) # &a ,dict(cid='orcn',tp='ch' ,t=5 ,l=5+300 ,w=40 ,cap=_('&OR') ,act='1' ) # &o ,dict( tp='lb' ,tid='orcn' ,l=5+5 ,w=90 ,cap=_('In &Command:') ,hint=ccnd_h) # &c ,dict(cid='ccnd',tp='ed' ,t=5+20 ,l=5+5 ,w=150 ) # ,dict( tp='lb' ,tid='orcn' ,l=5+350+5 ,w=50 ,cap=_('In &Snip(s):') ,hint=scnd_h) # &s ,dict(cid='shlp',tp='bt' ,tid='orcn' ,l=5+350+5+80,w=20 ,cap=_('&?') ) # &? ,dict(cid='scnd',tp='ed' ,t=5+20 ,l=5+350+5 ,w=100 ) # ,dict(cid='lwcs',tp='lvw' ,t=5+50 ,l=5 ,w=520,h=535 ,items=itms ,props='1' ) # grid ,dict(cid='asnp',tp='bt' ,t=200 ,l=5+520+5 ,w=110 ,cap=_('A&dd Snip') ) # &d ,dict(cid='rsnp',tp='bt' ,t=200+30 ,l=5+520+5 ,w=110 ,cap=_('F&ree Snip(s)') ) # &r ,dict(cid='help',tp='bt' ,t=600-65 ,l=5+520+5 ,w=110 ,cap=_('Hel&p') ) # &p ,dict(cid='-' ,tp='bt' ,t=600-35 ,l=5+520+5 ,w=110 ,cap=_('Close') ) # ] lwcs_n = -1 if 0==len(fi_l) else \ 0 if cmd_id not in fi_l else \ fi_l.index(cmd_id) pass; # LOG and log('stat, lwcs_n={}',(stat, lwcs_n)) vals = dict(ccnd=ccnd ,scnd=scnd ,orcn=orcn ,lwcs=lwcs_n) pass; #LOG and log('in-vals={}',(vals)) btn, vals, chds = dlg_wrapper(_('Configure "SnipToCall"'), 650-5, 600, cnts, vals, focus_cid=focused) pass; #LOG and log('an-vals={}',(vals)) pass; #LOG and log('chds={}',(chds)) if btn is None or btn=='-': return#while True focused = chds[0] if 1==len(chds) else focused ccnd = vals['ccnd'].strip() scnd = vals['scnd'].strip() orcn = vals['orcn'] lwcs_n = vals['lwcs'] cmd_id = '' if lwcs_n==-1 else fi_l[lwcs_n] if False:pass elif btn in 'fltr': focused = 'lwcs' elif btn=='drop': ccnd = '' scnd = '' focused = 'ccnd' elif btn=='shlp': app.msg_box(sndt.snip_help, app.MB_OK) elif btn=='help': dlg_wrapper(_('Help for "Config SnipToCall"'), 410, 310, [dict(cid='htxt',tp='me' ,t=5 ,h=300-28,l=5 ,w=400 ,props='1,0,1' ) # ro,mono,border ,dict(cid='-' ,tp='bt' ,t=5+300-23 ,l=5+400-80 ,w=80 ,cap=_('&Close')) ], dict(htxt=f(_('• In Command.' '\r{ccnd_h}' '\r ' '\r• In Snip. ' '\r{scnd_h}' '\r '), ccnd_h=ccnd_h, scnd_h=scnd_h) ), focus_cid='htxt') elif btn=='rsnp' and cmd_id: cnm = sndt.get_name(cmd_id) snp_l = sndt.get_snips(cmd_id) snps = ', '.join(snp_l) if app.msg_box(f(_('Do you want to remove snip(s) ' '\n {}' '\nfor command "{}"?') , snps, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: continue#while for snp in snp_l: sndt.free(snp) elif btn=='asnp' and cmd_id: cnm = sndt.get_name(cmd_id) new_sn = app.dlg_input(f(_('Add snip for "{}"'), cnm), '') if not new_sn: continue#while while not SnipData.is_snip(new_sn): app.msg_status(SnipData.msg_correct_snip) new_sn = app.dlg_input(f(_('Snip for "{}"'), cnm), new_sn) if not new_sn: break if not new_sn: continue#while pre_cid = sndt.get_cmdid(new_sn) if pre_cid: pre_cnm = sndt.get_name(pre_cid) if app.msg_box(f(_('Snip "{}" is already assigned ' '\nto command "{}".' '\n' '\nDo you want to reassign the snip ' '\nto command "{}"?') , new_sn, pre_cnm, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: continue#while sndt.set(new_sn, cmd_id)
def do_work(self, aid, ag): m,M = self,CfgKeysDlg lwks_n = ag.cval('lwks') if lwks_n==-1: return [] #continue#while m.cmd_id = m.fl_Is[lwks_n] if False:pass elif aid in ('del1', 'del2'): # Delete the hotkeys cmd_nkk = m.id2nkks[m.cmd_id] del_i = 1 if aid=='del1' else 2 if not cmd_nkk[del_i]: return [] #continue#while cmd_nkk[del_i] = '' if cmd_nkk[2]: cmd_nkk[1] = cmd_nkk[2] cmd_nkk[2] = '' set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', m.cmd_id, cmd_nkk[1], cmd_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', m.cmd_id) m.nkki_l, \ m.id2nkks, \ m.ks2id = M.prep_keys_info() elif aid in ('add1', 'add2'): ext_k = app.dlg_hotkey() pass; #LOG and log('ext_k={}',(ext_k,)) if ext_k is None: return [] #continue#while cmd_nkk = m.id2nkks[m.cmd_id] add_i = 1 if aid=='add1' else 2 old_k = cmd_nkk[add_i] new_k = old_k + ' * ' + ext_k if old_k else ext_k pass; #LOG and log('cmd_nkk,old_k,new_k={}',(cmd_nkk,old_k,new_k)) if new_k in m.ks2id: dbl_id = m.ks2id[new_k] dbl_nkk = m.id2nkks[dbl_id] if app.msg_box(f(_('Hotkey "{}" is already assigned ' '\nto command "{}".' '\n' '\nDo you want to reassign the hotkey ' '\nto selected command "{}"?') , new_k, dbl_nkk[0], cmd_nkk[0]), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while dbl_i = 1 if dbl_nkk[1]==new_k else 2 pass; #LOG and log('dbl_id, dbl_nkk={}',(dbl_id, dbl_nkk)) dbl_nkk[dbl_i] = '' if dbl_nkk[2]: dbl_nkk[1], dbl_nkk[2] = dbl_nkk[2], '' pass; #LOG and log('dbl_id, dbl_nkk={}',(dbl_id, dbl_nkk)) set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', dbl_id, dbl_nkk[1], dbl_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', dbl_id) cmd_nkk[add_i] = new_k pass; #LOG and log('cmd_id, cmd_nkk={}',(cmd_id, cmd_nkk)) set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', m.cmd_id, cmd_nkk[1], cmd_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', m.cmd_id) m.nkki_l, \ m.id2nkks, \ m.ks2id = M.prep_keys_info() elif aid=='asnp' and sndt: cnm = sndt.get_name(m.cmd_id) new_sn = app.dlg_input(f(_('Add snip for "{}"'), cnm), '') if not new_sn: return [] #continue#while while not SnipData.is_snip(new_sn): app.msg_status(SnipData.msg_correct_snip) new_sn = app.dlg_input(f(_('Snip for "{}"'), cnm), new_sn) if not new_sn: break if not new_sn: return [] #continue#while pre_cid = sndt.get_cmdid(new_sn) if pre_cid: pre_cnm = sndt.get_name(pre_cid) if app.msg_box(f(_('Snip "{}" is already assigned ' '\nto command "{}".' '\n' '\nDo you want to reassign the snip ' '\nto command "{}"?') , new_sn, pre_cnm, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while sndt.set(new_sn, cmd_id) elif aid=='rsnp' and sndt: cnm = sndt.get_name(m.cmd_id) snp_l = sndt.get_snips(m.cmd_id) snps = ', '.join(snp_l) if app.msg_box(f(_('Do you want to remove snip(s) ' '\n {}' '\nfor command "{}"?') , snps, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while for snp in snp_l: sndt.free(snp) return dict(ctrls=self.get_cnts('lwks') , vals =self.get_vals('lwks') , fid ='lwks' )
def on_macro(self, ed_self, mcr_record): ''' Finish for macro-recording. Params mcr_record "\n"-separated list of number number,string py:string_module,string_method,string_param ''' pass LOG and log('mcr_record={}', mcr_record) if '' == mcr_record: return app.msg_status('Empty record') def_nm = '' nms = [mcr['nm'] for mcr in self.macros] for num in range(1, 1000): def_nm = 'Macro{}'.format(num) if def_nm not in nms: break #for num while True: mcr_nm = app.dlg_input( 'Macro name. Tricks: "!NM" overwrite NM, "=NM" show NM in dialog', def_nm) if mcr_nm is None: return mcr_nm = mcr_nm.strip() if '' == mcr_nm: continue #while if mcr_nm[0] == '=': self.need_dlg = True mcr_nm = mcr_nm[1:] use_old = False if '' == mcr_nm: continue #while if mcr_nm[0] == '!': use_old = True mcr_nm = mcr_nm[1:] if '' != mcr_nm: break #while pass LOG and log('self.need_dlg, use_old, mcr_nm={}', (self.need_dlg, use_old, mcr_nm)) if use_old and mcr_nm in nms: mcr_ind = nms.index(mcr_nm) self.macros[mcr_ind]['rec'] = mcr_record self.macros[mcr_ind]['evl'] = self._record_data_to_cmds(mcr_record) id4mcr = self.macros[mcr_ind]['id'] else: while mcr_nm in nms: app.msg_box( 'Select other name.\nMacros names now:\n\n' + '\n'.join(nms), app.MB_OK) mcr_nm = app.dlg_input('Macro name', mcr_nm) if mcr_nm is None: return id4mcr = random.randint(10000, 99999) while id4mcr in self.mcr4id: id4mcr = random.randint(10000, 99999) self.macros += [{ 'id': id4mcr ##?? conflicts? , 'nm': mcr_nm, 'rec': mcr_record, 'evl': self._record_data_to_cmds(mcr_record) }] self._do_acts() if self.need_dlg: self.need_dlg = False self.last_mcr_id = id4mcr self.dlg_config()