Tuesday 21 June 2011

Tip: Opening a file with a non-default application - Part II

Looking back at my last post, I just realised that the Mac version might not work properly. The shell path of a folder item in RealBasic is an 'escaped string'. This means that a file path such as /Users/markoxley/Desktop/Untitled Folder would end up as /Users/markoxley/Desktop/Untitled\ Folder (note the back slash before the space in 'Untitled Folder').

To fix this, we can implement a very simple function:

 

Sub UnEscape(value As String) As String

 Dim s As String

  Dim index as integer=0

  while index<Len(value)

    index=index+1

    if mid(value,index,1)="\" then

      if index<>Len(value) then 

        index=index+1

        s=s+mid(value,index,1)

      end if

    else

      s=s+mid(value,index,1)

    end if

  wend 

  Return s

End Sub

We would then replace the original subroutine with this:

 

Sub OpenFileWith(DocumentPath As FolderItem, ApplicationPath As FolderItem)

  Dim ShellString As String

  Dim sh As Shell=New Shell

  #if TargetMacOS

    ShellString="open -a '" + UnEscape(ApplicationPath.ShellPath) + "' '" + UnEscape(DocumentPath.ShellPath) + "'"

  #elseif TargetWin32

    ShellString=ApplicationPath.AbsolutePath + " " + DocumentPath.AbsolutePath

  #endif

  

  sh.Execute(ShellString)

End Sub

Sunday 5 June 2011

Tip: Opening a file with a non-default application

I have worked on a couple of projects which have required me to designate an application to open a file and in some circumstances, this is not the default application. Therefore, I came up with a small routine in RealBasic to do this (only Mac and Windows I'm afraid)

 

Sub OpenFileWith(DocumentPath As FolderItem, ApplicationPath As FolderItem)

  Dim ShellString As String

  Dim sh As Shell=New Shell

  #if TargetMacOS

    ShellString="open -a '" + ApplicationPath.ShellPath + "' '" + DocumentPath.ShellPath + "'"

  #elseif TargetWin32

    ShellString=ApplicationPath.AbsolutePath + " " + DocumentPath.AbsolutePath

  #endif

  

  sh.Execute(ShellString)

End Sub

 

On a Mac, it also appears that you can open the application by just using its name, so this can also be addressed by the overriding the subroutine with the following:

 

Sub OpenFileWith(DocumentPath As FolderItem, ApplicationName As String)

  #if TargetMacOS

    Dim ShellString As String

    Dim sh As Shell=New Shell

    ShellString="open -a '" + ApplicationName + "' '" + DocumentPath.ShellPath + "'"

    sh.Execute(ShellString)

  #endif

End Sub

 

Hope this helps anyone else who needs to do something like this.