Applescript拖放不起作用

时间:2016-09-03 22:02:34

标签: drag-and-drop applescript

我是Applescript的新手,并编写了一个脚本来安全地擦除文件,这会打开一个文件选择对话框并进行确认,然后擦除文件。但是,当我尝试添加拖放功能时,它并不像每个人都说的那样工作。图标从不突出显示(表示拖放工作正常),Finder只是将文件复制到应用程序的文件夹而不是拖到应用程序上!

这是原始脚本,工作正常(保存为"擦除File.app"):

on run
    set the_file to choose file with prompt "Select the file to wipe:"
    wipe_file(the_file)
end run

to wipe_file(file_to_wipe)
    set file_to_wipe to POSIX path of file_to_wipe
    set ok_to_wipe to display dialog "Are you sure you want to wipe \"" & file_to_wipe & "\"?" buttons {"Cancel", "OK"} default button "Cancel"
    set ok_to_wipe to button returned of ok_to_wipe
    if (ok_to_wipe = "OK") then
        tell application "Terminal"
            activate
            do script "set prompt='';cls;srm -v \"" & file_to_wipe & "\""
            delay 3
            close front window
            set still_active to count windows
            if still_active = 0 then
                quit
            end if
        end tell
    end if
end wipe_file

然后我将以下内容添加到顶部。运行脚本仍然可以使用文件选择对话框,但系统永远不允许拖放!

on open the_files
    repeat with the_file in the_files
        wipe_file(the_file)
    end repeat
end open

我看到的每个地方(谷歌,堆栈溢出)都说这种方法应该有效,但它并没有。我甚至尝试删除on run...块,只留下on open...,但后来脚本什么也没做。

修改

如果我使用上面的内容创建一个新脚本,并将其另存为应用程序,则将其复制到“应用程序”文件夹,然后将自定义图标粘贴到其上,拖放即可。然而,旧的剧本原本没有在开放的#34;支持,即使在"开放"之后仍然无法工作支持已添加到脚本中。所以现在我认为Apple必须设置一些特殊的属性来指示脚本支持拖放,并且由于某种原因(因为它在我第一次保存时没有它?)Apple没有为我的文件设置该属性。查看两个应用程序的获取信息和显示包内容,存在一些奇怪的差异:

  1. 新创建的(工作)应用程序只有693 KB,但旧的(假设相同,但已损坏)应用程序是9.4 MB!
  2. 在Contents / MacOS文件夹中,新(工作)应用程序有一个名为" droplet"的文件,而旧的(已损坏)应用程序有一个名为" applet"的文件。
  3. 第一个是奇怪的,让我想到某种文件损坏,但第二个显然是苹果用于拖放的神奇设置。我确认如果我删除" on open"从工作脚本中阻止并保存,Apple会更新脚本图标以删除" drop"箭头,你仍然可以将文件拖放到它上面,但没有任何反应。

    所以Apple似乎决定脚本是否支持第一次保存脚本时拖放,之后你会得到错误的结果,除非保存一个全新的脚本!

1 个答案:

答案 0 :(得分:0)

您无需呼叫终端并打开窗口。 'do shell script'已在后台打开一个shell会话,在终端中不可见。你必须在'try / end try'块中使用它,以避免脚本在发生错误时停止(比如没有文件授权!)

此外,您正在使用带有选项v(详细)的'srm'。此选项用于显示正在执行的操作,但由于您正在关闭窗口,因此您看不到它。

当您的文件路径包含必须在shell中转义的特殊字符时,您的脚本可能出现问题。为避免这种情况,请使用'引用形式'。

测试脚本如下:

on run
set the_file to choose file with prompt "Select the file to wipe:"
wipe_file(the_file)
end run

on open the_files
repeat with the_file in the_files
    wipe_file(the_file)
end repeat
end open

to wipe_file(file_to_wipe)
set file_to_wipe to POSIX path of file_to_wipe
set ok_to_wipe to display dialog "Are you sure you want to wipe \"" & file_to_wipe & "\"?" buttons {"Cancel", "OK"} default button "Cancel"
if (button returned of ok_to_wipe = "OK") then
    try
        do shell script "srm " & quoted form of (file_to_wipe)
    end try
end if
end wipe_file