def paste(self):
# ImageFile.LOAD_TRUNCATED_IMAGES = True
dirname = os.path.dirname(__file__)
command = ['/usr/bin/python3', os.path.join(dirname, 'bin/imageutil.py'), 'grab']
abs_fn, rel_fn = self.get_filename()
tempfile1 = "/tmp/imagepaste1.png"
command.append(tempfile1)
out = self.run_command(" ".join(command))
if out[:4] == "grab":
ret = sublime.ok_cancel_dialog("save to file?")
print("ret %r" % ret)
if ret:
shutil.move(tempfile1, abs_fn)
return rel_fn
else:
return None
# im = ImageGrab.grabclipboard()
# if im:
# abs_fn, rel_fn = self.get_filename()
# im.save(abs_fn,'PNG')
# return rel_fn
else:
print('clipboard buffer is not image!')
return None
python类ok_cancel_dialog()的实例源码
def run(self):
"""Run the command."""
if not sublime.ok_cancel_dialog(
'You will be asked for the linter name. Please enter the name '
'of the linter binary (including dashes), NOT the name of the language being linted. '
'For example, to lint CSS with csslint, the linter name is '
'“csslint”, NOT “css”.',
'I understand'
):
return
self.window.show_input_panel(
'Linter name:',
'',
on_done=self.copy_linter,
on_change=None,
on_cancel=None)
def run(self):
"""Run the command."""
if not sublime.ok_cancel_dialog(
'You will be asked for the linter name. Please enter the name '
'of the linter binary (including dashes), NOT the name of the language being linted. '
'For example, to lint CSS with csslint, the linter name is '
'“csslint”, NOT “css”.',
'I understand'
):
return
self.window.show_input_panel(
'Linter name:',
'',
on_done=self.copy_linter,
on_change=None,
on_cancel=None)
def on_node_js_path_provided(self, path):
log_debug("Node.js path provided: " + path)
if os.path.exists(path):
log_debug("Node.js path is valid")
settings = self.load_settings()
if EI_BUILDER_SETTINGS not in settings:
settings[EI_BUILDER_SETTINGS] = {}
builder_settings = settings[EI_BUILDER_SETTINGS]
builder_settings[EI_ST_PR_NODE_PATH] = path
self.env.project_manager.save_settings(PR_SETTINGS_FILE, settings)
else:
if sublime.ok_cancel_dialog(STR_INVALID_NODE_JS_PATH):
self.prompt_for_node_js_path(False)
# Loop back to the main settings check
self.check_settings()
def on_builder_cli_path_provided(self, path):
log_debug("Builder CLI path provided: " + path)
if os.path.exists(path):
log_debug("Builder CLI path is valid")
settings = self.load_settings()
if EI_BUILDER_SETTINGS not in settings:
settings[EI_BUILDER_SETTINGS] = {}
builder_settings = settings[EI_BUILDER_SETTINGS]
builder_settings[EI_ST_PR_BUILDER_CLI] = path
self.env.project_manager.save_settings(PR_SETTINGS_FILE, settings)
else:
if sublime.ok_cancel_dialog(STR_INVALID_BUILDER_CLI_PATH):
self.prompt_for_node_js_path(False)
# Loop back to the main settings check
self.check_settings()
def on_model_name_provided(self, name):
response, code = HTTP.post(self.env.project_manager.get_build_api_key(),
PL_BUILD_API_URL_V4 + "models/", '{"name" : "' + name + '" }')
if not HTTP.is_response_code_valid(code) \
and sublime.ok_cancel_dialog(STR_MODEL_NAME_EXISTS):
self.create_new_model(False)
return
elif not HTTP.is_response_code_valid(code):
sublime.message_dialog(STR_MODEL_FAILED_TO_CREATE)
return
# Save newly created model to the project settings
settings = self.load_settings()
settings[EI_MODEL_ID] = response.get("model").get("id")
settings[EI_MODEL_NAME] = response.get("model").get("name")
self.env.project_manager.save_settings(PR_SETTINGS_FILE, settings)
self.update_model_name_in_status(query_model_name=False)
# Reset the logs
self.env.log_manager.reset()
# Check settings
self.check_settings(selecting_or_creating_model=True)
def add_device(self, need_to_confirm=True):
model = self.load_this_model()
if not model:
sublime.message_dialog(STR_MODEL_NOT_ASSIGNED)
return
if need_to_confirm and not sublime.ok_cancel_dialog(STR_MODEL_ADD_DEVICE): return
device_ids = model.get("devices")
(device_ids, device_names) = self.load_devices(exclude_device_ids=device_ids)
if len(device_ids) == 0:
sublime.message_dialog(STR_NO_DEVICES_AVAILABLE)
return
self.env.tmp_model = model
self.env.tmp_device_ids = device_ids
self.window.show_quick_panel(device_names, self.on_device_to_add_selected)
def on_build_api_key_provided(self, key):
log_debug("build api key provided: " + key)
if HTTP.is_build_api_key_valid(key):
log_debug("build API key is valid")
self.env.project_manager.save_settings(PR_AUTH_INFO_FILE, {
EI_BUILD_API_KEY: key,
EI_BUILDER_SETTINGS: {
EI_GITHUB_USER: None,
EI_GITHUB_TOKEN: None
}
})
else:
if sublime.ok_cancel_dialog(STR_INVALID_API_KEY):
self.prompt_for_build_api_key(False)
# Loop back to the main settings check
self.check_settings()
def _delete_file(self, filepath):
if not filepath:
return
elif not os.path.isfile(filepath):
sublime.error_message("%s is not a file" % filepath)
return
if not sublime.ok_cancel_dialog("Delete this file?\n%s" % filepath):
return
vcs_tracking = (self.file_tracked_by_git(filepath) and
self.settings.get(VCS_MANAGEMENT_SETTING))
self.close_view(filepath)
if vcs_tracking:
self._git_rm(filepath)
else:
self._execute_delete_file(filepath)
self.refresh_sidebar()
def _create_project(self):
os.makedirs(self.project_dir, exist_ok=True)
if not os.path.exists(self.project_dir):
sublime.error_message("Could not create directory %s" % self.project_dir)
os.makedirs(os.path.join(self.project_dir, "src"), exist_ok=True)
with open(os.path.join(self.project_dir, "CMakeLists.txt"), "w") as f:
f.write(CMAKELISTS_FILE.format(self.project_name, self.type))
with open(os.path.join(self.project_dir, "src", "main." + self.suffix), "w") as f:
if self.type == "C":
f.write(CFILE)
else:
f.write(CXXFILE)
with open(os.path.join(self.project_dir, "src", "CMakeLists.txt"), "w") as f:
f.write(CMAKELISTS_SRC_FILE.format(self.suffix))
project_file = os.path.join(self.project_dir, self.project_name + ".sublime-project")
with open(project_file, "w") as f:
f.write(PROJECTFILE)
if sublime.ok_cancel_dialog('Select the file %s in "%s" in the upcoming prompt...' % (self.project_name + ".sublime-project", self.project_dir)):
sublime.run_command("prompt_open_project_or_workspace")
def run(self, edit):
files = self.get_marked() or self.get_selected()
if files:
# Yes, I know this is English. Not sure how Sublime is translating.
if len(files) == 1:
msg = "Delete {}?".format(files[0])
else:
msg = "Delete {} items?".format(len(files))
if sublime.ok_cancel_dialog(msg):
for filename in files:
fqn = join(self.path, filename)
if isdir(fqn):
shutil.rmtree(fqn)
else:
os.remove(fqn)
self.view.run_command('dired_refresh')
def run_script_on_file(self, temp_file_path):
try:
node_path = PluginUtils.get_node_path()
script_path = PLUGIN_FOLDER + "/scripts/run.js"
file_path = self.view.file_name()
cmd = [node_path, script_path, temp_file_path, file_path or "?"]
output = SoliumGutterCommand.get_output(cmd)
print(output)
if output.find(OUTPUT_VALID) != -1:
output = output.decode('utf-8');
return output
print(output)
raise Exception(output)
except:
# Something bad happened.
print("Unexpected error({0}): {1}".format(sys.exc_info()[0], sys.exc_info()[1]))
# Usually, it's just node.js not being found. Try to alleviate the issue.
msg = "Node.js was not found in the default path. Please specify the location."
if not sublime.ok_cancel_dialog(msg):
msg = "You won't be able to use this plugin without specifying the path to node.js."
sublime.error_message(msg)
else:
PluginUtils.open_sublime_settings(self.view.window())
def replace_confirming(self, edit, pattern, compiled_rx, replacement,
replace_count, target_region):
last_row = row_at(self.view, target_region.b - 1)
start = target_region.begin()
while True:
match = self.view.find(pattern, start)
# no match or match out of range -- stop
if (match == R(-1)) or (row_at(self.view, match.a) > last_row):
self.view.show(first_sel(self.view).begin())
return
size_before = self.view.size()
with adding_regions(self.view, 's_confirm', [match], 'comment'):
self.view.show(match.a, True)
if sublime.ok_cancel_dialog("Confirm replacement?"):
text = self.view.substr(match)
substituted = re.sub(compiled_rx, replacement, text, count=replace_count)
self.view.replace(edit, match, substituted)
start = match.b + (self.view.size() - size_before)
def on_text_command(self, view, command_name, args):
# log('cmd={cmd} args={args}'.format(cmd=command_name, args=args))
if RemoteCppListFilesCommand.owns_view(view) and \
command_name == 'insert' and args['characters'] == '\n':
all_lines = get_multiple_sel_lines(view)
paths = []
for line in all_lines:
if self._is_valid_path(line):
paths.append(line)
def run_in_background():
for path in paths:
file = File(cwd=s_cwd(), path=path)
Commands.open_file(view, file.to_args())
if len(paths) > 10:
msg = ('This will open {0} files which could be slow. \n'
'Are you sure you want to do that?').format(len(paths),)
button_text = 'Open {0} Files'.format(len(paths))
if not sublime.ok_cancel_dialog(msg, button_text):
return None
THREAD_POOL.run(run_in_background)
return None
def replace_confirming(self, edit, pattern, compiled_rx, replacement,
replace_count, target_region):
last_row = row_at(self.view, target_region.b - 1)
start = target_region.begin()
while True:
match = self.view.find(pattern, start)
# no match or match out of range -- stop
if (match == Region(-1)) or (row_at(self.view, match.a) > last_row):
self.view.show(first_sel(self.view).begin())
return
size_before = self.view.size()
with adding_regions(self.view, 's_confirm', [match], 'comment'):
self.view.show(match.a, True)
if ok_cancel_dialog("Confirm replacement?"):
text = self.view.substr(match)
substituted = re.sub(compiled_rx, replacement, text, count=replace_count)
self.view.replace(edit, match, substituted)
start = match.b + (self.view.size() - size_before)
# https://vimhelp.appspot.com/change.txt.html#:delete
def report_error(message, project):
if sublime.ok_cancel_dialog(message, "Disable Tern"):
project.disabled = True
def plugin_loaded():
global arghints_enabled, renderer, tern_command, tern_arguments
global arg_completion_enabled
arghints_enabled = get_setting("tern_argument_hints", False)
arg_completion_enabled = get_setting("tern_argument_completion", False)
if "show_popup" in dir(sublime.View):
default_output_style = "tooltip"
else:
default_output_style = "status"
output_style = get_setting("tern_output_style", get_setting("tern_argument_hints_type", default_output_style))
renderer = create_renderer(output_style)
tern_arguments = get_setting("tern_arguments", [])
if not isinstance(tern_arguments, list):
tern_arguments = [tern_arguments]
tern_command = get_setting("tern_command", None)
if tern_command is None:
if not os.path.isdir(os.path.join(plugin_dir, "node_modules/tern")):
if sublime.ok_cancel_dialog(
"It appears Tern has not been installed. Do you want tern_for_sublime to try and install it? "
"(Note that this will only work if you already have node.js and npm installed on your system.)"
"\n\nTo get rid of this dialog, either uninstall tern_for_sublime, or set the tern_command setting.",
"Yes, install."):
try:
if hasattr(subprocess, "check_output"):
subprocess.check_output(["npm", "install"], cwd=plugin_dir)
else:
subprocess.check_call(["npm", "install"], cwd=plugin_dir)
except (IOError, OSError) as e:
msg = "Installation failed. Try doing 'npm install' manually in " + plugin_dir + "."
if hasattr(e, "output"):
msg += " Error message was:\n\n" + e.output
sublime.error_message(msg)
return
tern_command = ["node", os.path.join(plugin_dir, "node_modules/tern/bin/tern"), "--no-port-file"]
def run(self, pack_textures=True):
path = INFOS.addon.media_path
if pack_textures:
utils.texturepacker(media_path=path,
settings=sublime.load_settings(SETTINGS_FILE))
utils.make_archive(folderpath=path,
archive=os.path.join(path, os.path.basename(path) + ".zip"))
if sublime.ok_cancel_dialog("Zip file created!\nDo you want to show it with a file browser?"):
webbrowser.open(path)
def on_done(self, index):
if index == -1:
return None
media_path = os.path.join(INFOS.addon.theme_path, self.themes[index])
utils.texturepacker(media_path=media_path,
settings=sublime.load_settings(SETTINGS_FILE),
xbt_filename=self.themes[index] + ".xbt")
if sublime.ok_cancel_dialog("Theme file created!\nDo you want to show it with a file browser?"):
webbrowser.open(media_path)
def run(self, paths = []):
feature_name = get_feature_name(get_path(paths))
if sublime.ok_cancel_dialog('Remove Feature: %s?' % feature_name, 'Remove'):
run_script(get_path(paths), 'rm_feature', [feature_name])
def run(self, paths = []):
p = get_path(paths)
feature_name = None
component_name = get_filename_without_ext(get_path(paths))
args = component_name
if is_feature_component(p):
feature_name = get_feature_name(p)
args = '%s/%s' % (feature_name, component_name)
if sublime.ok_cancel_dialog('Remove Component: %s?' % args, 'Remove'):
Window().run_command('close')
run_script(get_path(paths), 'rm_component', [args])
def run(self, paths = []):
feature_name = get_feature_name(get_path(paths))
page_name = get_filename_without_ext(get_path(paths))
if sublime.ok_cancel_dialog('Remove Page: %s/%s?' % (feature_name, page_name), 'Remove'):
Window().run_command('close')
run_script(get_path(paths), 'rm_page', ['%s/%s' % (feature_name, page_name)])
def run(self, paths = []):
p = get_path(paths)
featureName = get_feature_name(p)
actionName = get_filename_without_ext(p)
if sublime.ok_cancel_dialog('Remove Action: %s/%s?' % (featureName, actionName), 'Remove'):
Window().run_command('close')
run_script(p, 'rm_action', ['%s/%s' % (featureName, actionName)])
def on_done(self, paths, relative_to_project, name):
if sublime.ok_cancel_dialog('Remove Action: %s?' % name, 'Remove'):
run_script(get_path(paths), 'rm_action', name.split(' '))
def run(self, paths = [], confirmed = 'False'):
if confirmed == 'False' and s.get('confirm_before_deleting', True):
if sublime.platform() == 'osx':
if sublime.ok_cancel_dialog('Delete the selected items?'):
self.run(paths, 'True')
else:
self.confirm([item.path() for item in SideBarSelection(paths).getSelectedItems()], [item.pathWithoutProject() for item in SideBarSelection(paths).getSelectedItems()])
else:
SideBarDeleteThread(paths).start()
def _delete_threaded(self, paths):
key = 'delete-'+str(time.time())
window_set_status(key, 'Deleting…')
try:
from .send2trash import send2trash
for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems():
if s.get('close_affected_buffers_when_deleting_even_if_dirty', False):
item.closeViews()
if s.get('disable_send_to_trash', False):
if sublime.platform() == 'windows':
self.remove('\\\\?\\'+item.path());
else:
self.remove(item.path());
else:
send2trash(item.path())
SideBarProject().refresh();
except:
should_confirm = s.get('confirm_before_permanently_deleting', True)
if not should_confirm or sublime.ok_cancel_dialog('There is no trash bin, permanently delete?', 'Yes, Permanent Deletion'):
for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems():
if s.get('close_affected_buffers_when_deleting_even_if_dirty', False):
item.closeViews()
if sublime.platform() == 'windows':
self.remove('\\\\?\\'+item.path());
else:
self.remove(item.path());
SideBarProject().refresh();
window_set_status(key, '')
def run(self, paths = [], confirmed = 'False'):
if confirmed == 'False' and s.get('confirm_before_deleting', True):
if sublime.platform() == 'osx':
if sublime.ok_cancel_dialog('empty the content of the folder?'):
self.run(paths, 'True')
else:
self.confirm([item.path() for item in SideBarSelection(paths).getSelectedDirectoriesOrDirnames()], [item.pathWithoutProject() for item in SideBarSelection(paths).getSelectedDirectoriesOrDirnames()])
else:
key = 'move-'+str(time.time())
SideBarEmptyThread(paths, key).start()
def overwrite(self):
overwrite = sublime.ok_cancel_dialog("Destination exists", "Delete, and overwrite")
if overwrite:
from SideBarEnhancements.send2trash import send2trash
send2trash(self.path())
return True
else:
return False
def run(self, edit):
ret = sublime.ok_cancel_dialog('Erase Customized Log Highlight Syntax & Theme ?')
if ret:
try:
wins_l = sublime.windows()
for w in wins_l:
s_view = w.get_output_panel('loghighlight')
if s_view:
w.run_command("hide_panel", {"panel": "output.loghighlight"})
s_view.set_syntax_file('Packages/Log Highlight/Log Highlight.tmLanguage')
s_view.settings().set('color_scheme', 'Packages/Log Highlight/Log Highlight.hidden-tmTheme')
view_l = w.views()
for v in view_l:
if check_syntax(v):
v.set_syntax_file('Packages/Log Highlight/Log Highlight.tmLanguage')
v.settings().set('color_scheme', 'Packages/Log Highlight/Log Highlight.hidden-tmTheme')
usr_syntax = os.path.join(sublime.packages_path(), 'User/Log Highlight.tmLanguage')
if os.path.exists(usr_syntax):
os.remove(usr_syntax)
usr_theme = os.path.join(sublime.packages_path(), 'User/Log Highlight.hidden-tmTheme')
if os.path.exists(usr_theme):
os.remove(usr_theme)
except Exception:
disp_exept()
## Log Highlight ____________________________________________
# to prevent re-run in short time
def run_script_on_file(self, temp_file_path):
try:
node_path = PluginUtils.get_node_path()
script_path = PLUGIN_FOLDER + "/scripts/run.js"
file_path = self.view.file_name()
cmd = [node_path, script_path, temp_file_path, file_path or "?", USER_FOLDER]
output = PluginUtils.get_output(cmd)
# Make sure the correct/expected output is retrieved.
if output.find(OUTPUT_VALID) != -1:
return output
msg = "Command " + '" "'.join(cmd) + " created invalid output."
print(output)
raise Exception(msg)
except:
# Something bad happened.
print("Unexpected error({0}): {1}".format(sys.exc_info()[0], sys.exc_info()[1]))
# Usually, it's just node.js not being found. Try to alleviate the issue.
msg = "Node.js was not found in the default path. Please specify the location."
if not sublime.ok_cancel_dialog(msg):
msg = "You won't be able to use this plugin without specifying the path to node.js."
sublime.error_message(msg)
else:
PluginUtils.open_sublime_settings(self.view.window())