diff --git a/Win32/AppIcons.cs b/Win32/AppIcons.cs index b916444a..6d19071e 100644 --- a/Win32/AppIcons.cs +++ b/Win32/AppIcons.cs @@ -13,6 +13,29 @@ namespace Bemo /// public static class AppIcons { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct StockIconInfo + { + public uint Size; + public IntPtr Icon; + public int SystemIndex, ResourceIndex; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Path; + } + [DllImport("shell32.dll", CharSet = CharSet.Unicode)] + private static extern int SHGetStockIconInfo(uint id, uint flags, ref StockIconInfo info); + + // The caller owns the copy; release the native shell handle immediately. + public static Icon GetStockIcon(uint id) + { + var info = new StockIconInfo { Size = (uint)Marshal.SizeOf(typeof(StockIconInfo)) }; + try + { + if (SHGetStockIconInfo(id, 0x100, ref info) < 0 || info.Icon == IntPtr.Zero) return null; + return (Icon)Icon.FromHandle(info.Icon).Clone(); + } + finally { if (info.Icon != IntPtr.Zero) WinUserApi.DestroyIcon(info.Icon); } + } + private delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam); [DllImport("shell32.dll", CharSet = CharSet.Unicode)] diff --git a/WtProgram/Commands.fs b/WtProgram/Commands.fs index 064163cd..f7046abb 100644 --- a/WtProgram/Commands.fs +++ b/WtProgram/Commands.fs @@ -410,6 +410,20 @@ module Commands = let current = Services.settings.getValue key :?> bool Services.settings.setValue(key,box (not current))) with listed=false } + let private iconChoices hwnd title restore current apply = + let pick (path,label) = choice label (if current=Some path then tr Strings.TabMenu.currentIcon else "") (fun () -> apply (Some path)) + let section label entries = { choice (tr label) "" ignore with concealed=false; run=fun () -> Choose(List.map pick entries) } + [ section Strings.TabMenu.systemTabIcons (TabIconChoices.windows |> List.map(fun (path,label) -> path,tr label)) + section Strings.TabMenu.commonTabIcons (TabIconChoices.common |> List.map(fun (path,label,_,_) -> path,tr label)) + let applications = TabIconChoices.applications() + if not applications.IsEmpty then section Strings.TabMenu.appTabIcons applications + let recent = TabIconChoices.recent Services.settings.root |> List.filter IO.File.Exists |> List.map(fun path -> path,IO.Path.GetFileName path) + if not recent.IsEmpty then section Strings.TabMenu.recentTabIcons recent + choice (tr Strings.TabMenu.chooseTabIconFile) "" (fun () -> + TabIconPicker.chooseFor title {new System.Windows.Forms.IWin32Window with member _.Handle=hwnd} + apply) + choice (tr restore) "" (fun () -> apply None) ] + let all : Command list = [ fromCatalog "next-tab" TabCommands hasOtherTabs (onGroup(fun g -> g.switchWindow(true,false))) fromCatalog "previous-tab" TabCommands hasOtherTabs (onGroup(fun g -> g.switchWindow(false,false))) @@ -469,6 +483,14 @@ module Commands = if canRememberGroupColor hwnd then yield choice (tr Strings.Settings.rememberGroupColor) (if (Services.program.getGroupColor hwnd).IsSome then "✓" else "") (fun () -> rememberGroupColor hwnd) yield choice (tr Strings.Settings.clearTabColor) "" (fun () -> clearTabColor hwnd) ]) + choosing "tab-icon" Strings.Commands.tabIcon TabCommands hasGroup (fun hwnd -> + iconChoices hwnd Strings.TabMenu.tabIcon Strings.TabMenu.restoreTabIcon (Services.program.getTabIcon hwnd) + (fun path -> onTab (fun g hwnd -> g.run(SetTabIcon(hwnd,path))) hwnd)) + plain "change-tab-icon" Strings.Commands.changeTabIcon TabCommands hasGroup (onTab(fun group hwnd -> + TabIconPicker.choose {new System.Windows.Forms.IWin32Window with member _.Handle=hwnd} + (fun path -> group.run(SetTabIcon(hwnd,path))))) + plain "restore-tab-icon" Strings.Commands.restoreTabIcon TabCommands (fun hwnd -> hasGroup hwnd && (Services.program.getTabIcon hwnd).IsSome) + (onTab (fun g hwnd -> g.run(SetTabIcon(hwnd,None)))) plain "custom-tab-color" Strings.Commands.customTabColor TabCommands hasGroup customTabColor plain "remember-tab-color" Strings.Commands.rememberTabColor TabCommands canRememberTabColor rememberTabColor plain "remember-group-color" Strings.Commands.rememberGroupColor TabCommands canRememberGroupColor rememberGroupColor @@ -589,10 +611,9 @@ module Commands = | _ -> ())) with state=fun hwnd -> if hasGroup hwnd then Some(combinesIcons hwnd) else None } // Only a group with combined icons has a taskbar button of its own to change. - plain "change-group-icon" Strings.Commands.changeGroupIcon GroupCommands combinesIcons (fun hwnd -> - use dialog = new System.Windows.Forms.OpenFileDialog(Title=tr Strings.TabMenu.changeTaskbarIcon, - Filter=Localization.plain Strings.TabMenu.taskbarIconFiles,CheckFileExists=true) - if dialog.ShowDialog()=System.Windows.Forms.DialogResult.OK then Services.program.setGroupIcon(hwnd,Some dialog.FileName)) + choosing "change-group-icon" Strings.Commands.changeGroupIcon GroupCommands combinesIcons (fun hwnd -> + iconChoices hwnd Strings.TabMenu.taskbarIcon Strings.TabMenu.restoreTaskbarIcon (Services.program.groupIcon hwnd) + (fun path -> Services.program.setGroupIcon(hwnd,path))) plain "restore-group-icon" Strings.Commands.restoreGroupIcon GroupCommands combinesIcons (fun hwnd -> Services.program.setGroupIcon(hwnd,None)) // The app's own switches: each shows whether it is on for the app in front, with or // without tabs, so their keys are held everywhere. diff --git a/WtProgram/GroupPlugins/SuperBarPlugin.fs b/WtProgram/GroupPlugins/SuperBarPlugin.fs index 9b381719..3c98a44a 100755 --- a/WtProgram/GroupPlugins/SuperBarPlugin.fs +++ b/WtProgram/GroupPlugins/SuperBarPlugin.fs @@ -181,40 +181,6 @@ type TaskbarBadgedIcon(icon:Icon, ?stacked:Icon list) = badged.Dispose() WinUserApi.DestroyIcon(handle) |> ignore -/// A picture the user chose for a group's taskbar button, read as an icon. -module GroupIconFile = - let private pictures = set [".png";".jpg";".jpeg";".bmp";".gif"] - /// An icon that owns its own copy of the bitmap's handle. - let private fromBitmap (bitmap:Bitmap) = - let handle = bitmap.GetHicon() - try (Icon.FromHandle(handle).Clone() :?> Icon) finally WinUserApi.DestroyIcon(handle) |> ignore - /// An .ico, a picture (square and whole, centred), or a program's or library's icon; None when - /// the file is gone or unreadable. - let load (path:string) : Icon option = - try - if not (IO.File.Exists path) then None - else - match IO.Path.GetExtension(path).ToLowerInvariant() with - | ".ico" -> Some(new Icon(path,Size(64,64))) - | extension when pictures.Contains extension -> - use source = new Bitmap(path) - let side = 128 - use square = new Bitmap(side,side,PixelFormat.Format32bppArgb) - do - use g = Graphics.FromImage(square) - g.InterpolationMode <- Drawing2D.InterpolationMode.HighQualityBicubic - let scale = float side/float (max source.Width source.Height) - let width,height = max 1 (int(float source.Width*scale)),max 1 (int(float source.Height*scale)) - g.DrawImage(source,Rectangle((side-width)/2,(side-height)/2,width,height)) - Some(fromBitmap square) - | _ -> - match AppIcons.GetFileIcon(path,64) with - | null -> Some(Icon.ExtractAssociatedIcon(path)) - | bitmap -> - use shell = bitmap - Some(fromBitmap shell) - with _ -> None - type TbButton = { icon : Icon /// The icons of the group's other apps, front-most first. diff --git a/WtProgram/ManagerViewService/Views/AppGroupingRulesView.fs b/WtProgram/ManagerViewService/Views/AppGroupingRulesView.fs index ebbd650a..fe5a475d 100644 --- a/WtProgram/ManagerViewService/Views/AppGroupingRulesView.fs +++ b/WtProgram/ManagerViewService/Views/AppGroupingRulesView.fs @@ -78,19 +78,10 @@ module ImgHelper = module ApplicationNames = /// ApplicationFrameHost.exe hosts every Store (UWP) app, so it stands for them all, under a /// name and icon that say so rather than the host's file name and blank icon. - let isWindowsApps (path:string) = AppIdentity.key path = "APPLICATIONFRAMEHOST.EXE" + let isWindowsApps path = WindowsAppsIcon.matches path let label (path:string) = if isWindowsApps path then tr Strings.AppRules.windowsApps else Path.GetFileName path /// Four squares in the Windows blue, which reads on light and dark alike. - let windowsAppsIcon() : Image = - let side = Dpi.scale 16 - let image = new Bitmap(side,side,Imaging.PixelFormat.Format32bppArgb) - use g = Graphics.FromImage(image) - use brush = new SolidBrush(Color.FromArgb(0,120,212)) - let gap = max 1 (side/16) - let square = (side-gap)/2 - for x,y in [0,0;square+gap,0;0,square+gap;square+gap,square+gap] do - g.FillRectangle(brush,x,y,square,square) - image :> Image + let windowsAppsIcon() : Image = WindowsAppsIcon.image (Dpi.scale 16) :> Image /// The icon the app shows on the taskbar (one of its windows), else the executable's own: /// packaged apps such as Electron ones carry a different icon in the exe than on their /// windows. A host without icons of its own (ApplicationFrameHost.exe) gets None rather diff --git a/WtProgram/Program.fs b/WtProgram/Program.fs index 57b754c8..42b2e53f 100644 --- a/WtProgram/Program.fs +++ b/WtProgram/Program.fs @@ -97,20 +97,23 @@ type Program(lifetime:LifetimeScope, ?settings:Settings) as this = let isDroppedAndAwaitingGrouping = Cell.create(Set2()) let browserDrags = HashSet() let windowColors = WindowTabColors() + let mutable windowIcons : Map = Map.empty // An immutable map swapped whole on the main thread, so tab strips on group threads // read renames without waiting for it: tab text is rebuilt on every title change. let mutable windowNameOverride : Map2 = Map2() let restoredCustomizations,pendingCustomizationCleanup = WindowCustomizations.restore WindowCustomizations.identity settingsManager.settingsJson do - for hwnd,name,color in restoredCustomizations do + for hwnd,name,color,icon in restoredCustomizations do + icon |> Option.iter(fun path -> windowIcons <- windowIcons.Add(hwnd,path)) windowNameOverride <- windowNameOverride.add hwnd name windowColors.setOverride hwnd color let saveWindowCustomizations() = let entries = os.windowsInZorder.toArray |> Array.choose(fun window -> let name = windowNameOverride.tryFind(window.hwnd).bind(id) let color = windowColors.getOverride window.hwnd - if name.IsNone && color.IsNone then None else Some(window.hwnd,name,color)) |> Array.toList + let icon = windowIcons.TryFind window.hwnd + if name.IsNone && color.IsNone && icon.IsNone then None else Some(window.hwnd,name,color,icon)) |> Array.toList let root = settingsManager.settingsJson root.["windowCustomizations"] <- WindowCustomizations.write WindowCustomizations.identity entries settingsManager.settingsJson <- root @@ -1095,6 +1098,7 @@ type Program(lifetime:LifetimeScope, ?settings:Settings) as this = isDroppedAndAwaitingGrouping.map(fun s -> s.remove hwnd) windowNameOverride <- windowNameOverride.remove hwnd windowColors.remove hwnd + windowIcons <- windowIcons.Remove hwnd VirtualDesktop.forget hwnd awaitingDesktop.Remove hwnd |> ignore @@ -1817,6 +1821,15 @@ type Program(lifetime:LifetimeScope, ?settings:Settings) as this = member x.getWindowNameOverride(hwnd) = windowNameOverride.tryFind(hwnd).bind(id) + member _.getTabIcon hwnd = windowIcons.TryFind hwnd + member _.setTabIcon(hwnd,path) = + windowIcons <- match path with Some path -> windowIcons.Add(hwnd,path) | None -> windowIcons.Remove hwnd + saveWindowCustomizations() + path |> Option.iter(fun path -> + let root = settingsManager.settingsJson + TabIconChoices.remember path root + settingsManager.settingsJson <- root) + member _.getTabColorOverride hwnd = windowColors.getOverride hwnd member _.setTabColorOverride((hwnd,color)) = windowColors.setOverride hwnd color @@ -1903,7 +1916,11 @@ type Program(lifetime:LifetimeScope, ?settings:Settings) as this = member x.setGroupIcon(hwnd,path) = this.groupIconKey hwnd |> Option.iter(fun key -> let icons = settingsManager.groupIcons - settingsManager.groupIcons <- match path with Some path -> icons.Add(key,path) | None -> icons.Remove key) + settingsManager.groupIcons <- match path with Some path -> icons.Add(key,path) | None -> icons.Remove key + path |> Option.iter(fun path -> + let root = settingsManager.settingsJson + TabIconChoices.remember path root + settingsManager.settingsJson <- root)) member x.appWindows = os.windowsInZorder.where(this.isAppWindow).map(fun w -> w.hwnd) diff --git a/WtProgram/Shared/ProgramTypes.fs b/WtProgram/Shared/ProgramTypes.fs index 34b41532..a79286c4 100755 --- a/WtProgram/Shared/ProgramTypes.fs +++ b/WtProgram/Shared/ProgramTypes.fs @@ -179,6 +179,8 @@ type IProgram = abstract member shutdown : unit -> unit abstract member setWindowNameOverride : (IntPtr * Option) -> unit abstract member getWindowNameOverride : IntPtr -> Option + abstract member getTabIcon : IntPtr -> string option + abstract member setTabIcon : IntPtr * string option -> unit abstract member getTabColorOverride : IntPtr -> TabColorChoice option abstract member setTabColorOverride : (IntPtr * TabColorChoice option) -> unit abstract member getTabColor : IntPtr * IntPtr list -> TabColorChoice option @@ -288,6 +290,7 @@ type GroupCommand = /// The strip's order: the windows named, in that order, then any not named in the order /// they had; the pinned ones kept first either way. | SetTabOrder of IntPtr list + | SetTabIcon of IntPtr * string option | SetTabColor of IntPtr * TabColorChoice option | SetTabPinned of IntPtr * bool | ToggleIconsOnly diff --git a/WtProgram/Shared/Services.fs b/WtProgram/Shared/Services.fs index ede54e9f..5a15ddb6 100755 --- a/WtProgram/Shared/Services.fs +++ b/WtProgram/Shared/Services.fs @@ -101,6 +101,8 @@ type DispatchedProgram(inner:IProgram, dispatcher:IDispatcher) = member _.setWindowNameOverride value = dispatcher.Send(fun () -> inner.setWindowNameOverride value) // Reads an immutable snapshot; called by tab strips on every title change. member _.getWindowNameOverride hwnd = inner.getWindowNameOverride hwnd + member _.getTabIcon hwnd = inner.getTabIcon hwnd + member _.setTabIcon(hwnd,path) = dispatcher.Send(fun () -> inner.setTabIcon(hwnd,path)) member _.getTabColorOverride hwnd = inner.getTabColorOverride hwnd member _.setTabColorOverride value = dispatcher.Send(fun () -> inner.setTabColorOverride value) member _.getTabColor(hwnd,peers) = dispatcher.Send(fun () -> inner.getTabColor(hwnd,peers)) diff --git a/WtProgram/Shared/Strings.fs b/WtProgram/Shared/Strings.fs index 053c931e..b4d02595 100644 --- a/WtProgram/Shared/Strings.fs +++ b/WtProgram/Shared/Strings.fs @@ -59,6 +59,35 @@ module Strings = let group = { en="In group"; zh="组内"; ja="グループ内"; ar="داخل المجموعة"; ko="그룹 내" } module TabMenu = + let taskbarIcon = { en="Taskbar icon"; zh="任务栏图标"; ja="タスクバーアイコン"; ar="أيقونة شريط المهام"; ko="작업 표시줄 아이콘" } + let iconDocument = { en="Document"; zh="文档"; ja="ドキュメント"; ar="مستند"; ko="문서" } + let iconDrive = { en="Drive"; zh="磁盘"; ja="ドライブ"; ar="قرص"; ko="드라이브" } + let iconPrinter = { en="Printer"; zh="打印机"; ja="プリンター"; ar="طابعة"; ko="프린터" } + let iconRecycle = { en="Recycle Bin"; zh="回收站"; ja="ごみ箱"; ar="سلة المحذوفات"; ko="휴지통" } + let commonTabIcons = { en="Common icons"; zh="常用图标"; ja="よく使うアイコン"; ar="أيقونات شائعة"; ko="일반 아이콘" } + let iconStar = { en="Star"; zh="星标"; ja="星"; ar="نجمة"; ko="별" } + let iconHeart = { en="Heart"; zh="爱心"; ja="ハート"; ar="قلب"; ko="하트" } + let iconHome = { en="Home"; zh="主页"; ja="ホーム"; ar="منزل"; ko="홈" } + let iconFolder = { en="Folder"; zh="文件夹"; ja="フォルダー"; ar="مجلد"; ko="폴더" } + let iconNote = { en="Notes"; zh="笔记"; ja="メモ"; ar="ملاحظات"; ko="메모" } + let iconBook = { en="Reading"; zh="阅读"; ja="読書"; ar="قراءة"; ko="독서" } + let iconWork = { en="Work"; zh="工作"; ja="仕事"; ar="عمل"; ko="업무" } + let iconTools = { en="Tools"; zh="工具"; ja="ツール"; ar="أدوات"; ko="도구" } + let iconMusic = { en="Music"; zh="音乐"; ja="音楽"; ar="موسيقى"; ko="음악" } + let iconGame = { en="Games"; zh="游戏"; ja="ゲーム"; ar="ألعاب"; ko="게임" } + let iconGlobe = { en="Web"; zh="网络"; ja="ウェブ"; ar="ويب"; ko="웹" } + let iconCoffee = { en="Break"; zh="休息"; ja="休憩"; ar="استراحة"; ko="휴식" } + let currentIcon = { en="Current"; zh="当前"; ja="現在"; ar="الحالي"; ko="현재" } + let tabIcon = { en="Tab icon"; zh="标签图标"; ja="タブアイコン"; ar="أيقونة علامة التبويب"; ko="탭 아이콘" } + let systemTabIcons = { en="Windows icons"; zh="Windows 常用图标"; ja="Windows アイコン"; ar="أيقونات Windows"; ko="Windows 아이콘" } + let appTabIcons = { en="Open applications"; zh="已打开的应用"; ja="開いているアプリ"; ar="التطبيقات المفتوحة"; ko="열린 앱" } + let recentTabIcons = { en="Recent custom icons"; zh="最近使用的自定义图标"; ja="最近のカスタムアイコン"; ar="الأيقونات المخصصة الأخيرة"; ko="최근 사용자 지정 아이콘" } + let iconApplication = { en="Application"; zh="应用"; ja="アプリ"; ar="تطبيق"; ko="앱" } + let iconInformation = { en="Information"; zh="信息"; ja="情報"; ar="معلومات"; ko="정보" } + let iconWarning = { en="Warning"; zh="警告"; ja="警告"; ar="تحذير"; ko="경고" } + let iconError = { en="Error"; zh="错误"; ja="エラー"; ar="خطأ"; ko="오류" } + let iconQuestion = { en="Question"; zh="问号"; ja="質問"; ar="سؤال"; ko="질문" } + let iconShield = { en="Shield"; zh="盾牌"; ja="シールド"; ar="درع"; ko="방패" } let closeSelected = { en="Close selected tabs"; zh="关闭选中的标签"; ja="選択したタブを閉じる"; ar="إغلاق علامات التبويب المحددة"; ko="선택한 탭 닫기" } let windowBehavior = { en="Window behavior"; zh="窗口行为"; ja="ウィンドウの動作"; ar="سلوك النوافذ"; ko="창 동작" } let groupTopmost = { en="Pin group on top"; zh="分组置顶"; ja="グループを常に手前に表示"; ar="إبقاء المجموعة في المقدمة"; ko="그룹을 항상 위에 고정" } @@ -128,6 +157,10 @@ module Strings = ar="لم يتم الدمج: لم يسمح Windows بنقل زر شريط المهام إلى سطح المكتب الافتراضي هذا" ko="합치지 않음: Windows가 작업 표시줄 버튼을 이 가상 데스크톱으로 옮기지 못했습니다" } /// For the group's own taskbar button, shown while its icons are combined. + let chooseTabIconFile = { en="Choose from file…"; zh="从文件选择…"; ja="ファイルから選択…"; ar="اختيار من ملف…"; ko="파일에서 선택…" } + let changeTabIcon = { en="Change tab icon…"; zh="更改标签图标…"; ja="タブアイコンを変更…"; ar="تغيير أيقونة علامة التبويب…"; ko="탭 아이콘 변경…" } + let restoreTabIcon = { en="Restore tab icon"; zh="恢复标签图标"; ja="タブアイコンを復元"; ar="استعادة أيقونة علامة التبويب"; ko="탭 아이콘 복원" } + let invalidTabIcon = { en="This file could not be read as an icon or image."; zh="无法将此文件读取为图标或图片。"; ja="このファイルをアイコンや画像として読み込めません。"; ar="تعذرت قراءة هذا الملف كأيقونة أو صورة."; ko="이 파일을 아이콘이나 이미지로 읽을 수 없습니다." } let changeTaskbarIcon = { en="Change taskbar icon…"; zh="更换任务栏图标…"; ja="タスクバーアイコンを変更…"; ar="تغيير أيقونة شريط المهام…"; ko="작업 표시줄 아이콘 변경…" } let restoreTaskbarIcon = { en="Restore taskbar icon"; zh="恢复默认任务栏图标"; ja="タスクバーアイコンを元に戻す"; ar="استعادة أيقونة شريط المهام"; ko="작업 표시줄 아이콘 복원" } /// The kinds named with their extensions, so programs are seen to be taken too. @@ -831,6 +864,10 @@ module Strings = description={ en="Every window of the group from the app of the tab in front, but the pinned ones."; zh="分组中属于当前标签所在应用的所有窗口,固定的标签除外。"; ja="グループ内で、前面のタブのアプリのウィンドウを、固定したタブを除いてすべて。"; ar="كل نوافذ المجموعة من تطبيق علامة التبويب الأمامية، عدا المثبتة."; ko="고정한 탭을 제외하고 그룹에서 현재 탭과 같은 앱의 창을 모두 닫습니다." } keywords=tabWords } let private iconNote = { en="For a group with combined taskbar icons."; zh="用于已合并任务栏图标的分组。"; ja="タスクバーアイコンをまとめたグループ用。"; ar="لمجموعة دُمجت أيقونات شريط المهام لها."; ko="작업 표시줄 아이콘을 합친 그룹용입니다." } + let private tabIconNote = { en="Customize this tab's picture, keeping the original icon at the bottom right."; zh="自定义此标签的图片,并在右下角保留原图标。"; ja="元のアイコンを右下に残し、このタブの画像を変更します。"; ar="تخصيص صورة علامة التبويب مع إبقاء الأيقونة الأصلية أسفل اليمين."; ko="원래 아이콘을 오른쪽 아래에 유지하며 이 탭의 그림을 변경합니다." } + let tabIcon = { caption=TabMenu.tabIcon; description=tabIconNote; keywords=tabWords } + let changeTabIcon = { caption=TabMenu.changeTabIcon; description=tabIconNote; keywords=tabWords } + let restoreTabIcon = { caption=TabMenu.restoreTabIcon; description=tabIconNote; keywords=tabWords } let changeGroupIcon = { caption=TabMenu.changeTaskbarIcon; description=iconNote; keywords={ en="picture image"; zh="图片 图像"; ja="画像 ピクチャ"; ar="صورة"; ko="그림 이미지" } } let restoreGroupIcon = { caption=TabMenu.restoreTaskbarIcon; description=iconNote; keywords={ en="default picture"; zh="默认 图片"; ja="既定 画像"; ar="افتراضي صورة"; ko="기본값 그림" } } let closeAllTabs = { caption={ en="Close all tabs"; zh="关闭全部标签"; ja="すべてのタブを閉じる"; ar="إغلاق جميع علامات التبويب"; ko="모든 탭 닫기" } diff --git a/WtProgram/Shared/TabIcons.fs b/WtProgram/Shared/TabIcons.fs new file mode 100644 index 00000000..dba7b3ba --- /dev/null +++ b/WtProgram/Shared/TabIcons.fs @@ -0,0 +1,251 @@ +namespace Bemo +open System +open Bemo.Json +open System.Drawing +open System.Drawing.Imaging +open System.Windows.Forms + +/// ApplicationFrameHost represents Windows apps collectively, as in App Rules. +module WindowsAppsIcon = + let matches (path:string) = AppIdentity.key path = "APPLICATIONFRAMEHOST.EXE" + let image side = + let image = new Bitmap(side,side,PixelFormat.Format32bppArgb) + use graphics = Graphics.FromImage image + use brush = new SolidBrush(Color.FromArgb(0,120,212)) + let gap = max 1 (side/16) + let square = (side-gap)/2 + for x,y in [0,0;square+gap,0;0,square+gap;square+gap,square+gap] do + graphics.FillRectangle(brush,x,y,square,square) + image + +/// Shared file loading for tab and taskbar custom icons. +module TabIconChoices = + let builtins = [ + "builtin:application",Strings.TabMenu.iconApplication,SystemIcons.Application + "builtin:information",Strings.TabMenu.iconInformation,SystemIcons.Information + "builtin:warning",Strings.TabMenu.iconWarning,SystemIcons.Warning + "builtin:error",Strings.TabMenu.iconError,SystemIcons.Error + "builtin:question",Strings.TabMenu.iconQuestion,SystemIcons.Question + "builtin:shield",Strings.TabMenu.iconShield,SystemIcons.Shield ] + let shell = [ + "builtin:windows-document",Strings.TabMenu.iconDocument,0u + "builtin:windows-folder",Strings.TabMenu.iconFolder,3u + "builtin:windows-drive",Strings.TabMenu.iconDrive,8u + "builtin:windows-network",Strings.TabMenu.iconGlobe,13u + "builtin:windows-printer",Strings.TabMenu.iconPrinter,16u + "builtin:windows-recycle",Strings.TabMenu.iconRecycle,31u ] + let windows = + (builtins |> List.map(fun (key,label,_) -> key,label)) @ (shell |> List.map(fun (key,label,_) -> key,label)) + let common = [ + "builtin:star",Strings.TabMenu.iconStar,0xE734,Color.Goldenrod + "builtin:heart",Strings.TabMenu.iconHeart,0xEB51,Color.Crimson + "builtin:home",Strings.TabMenu.iconHome,0xE80F,Color.SeaGreen + "builtin:folder",Strings.TabMenu.iconFolder,0xE838,Color.DarkOrange + "builtin:note",Strings.TabMenu.iconNote,0xE70B,Color.SteelBlue + "builtin:book",Strings.TabMenu.iconBook,0xE8F1,Color.Sienna + "builtin:work",Strings.TabMenu.iconWork,0xE821,Color.SlateBlue + "builtin:tools",Strings.TabMenu.iconTools,0xE90F,Color.SlateGray + "builtin:music",Strings.TabMenu.iconMusic,0xEC4F,Color.DarkMagenta + "builtin:game",Strings.TabMenu.iconGame,0xE7FC,Color.ForestGreen + "builtin:globe",Strings.TabMenu.iconGlobe,0xE909,Color.Teal + "builtin:coffee",Strings.TabMenu.iconCoffee,0xEC32,Color.Chocolate ] + let recent (root:Bemo.Json.JObject) = + match root.["recentTabIcons"] with + | :? Bemo.Json.JArray as items -> + items |> Seq.choose(fun item -> if item.Type=Bemo.Json.JTokenType.String then Some(item.Value()) else None) + |> Seq.filter(fun path -> not(String.IsNullOrWhiteSpace path)) |> Seq.distinctBy(fun path -> path.ToUpperInvariant()) |> Seq.truncate 10 |> Seq.toList + | _ -> [] + let remember (path:string) root = + if not(path.StartsWith("builtin:",StringComparison.Ordinal)) then + let paths = path :: (recent root |> List.filter(fun saved -> not(String.Equals(saved,path,StringComparison.OrdinalIgnoreCase)))) |> List.truncate 10 + root.["recentTabIcons"] <- Bemo.Json.JArray(paths |> List.map(fun value -> Bemo.Json.JValue(value) :> Bemo.Json.JToken)) + let applications() = + Services.program.appWindows.list |> List.choose(fun hwnd -> + try + let pid = OS().windowFromHwnd(hwnd).pid + let path = pid.processPath + if String.IsNullOrEmpty path then None else Some(path,if WindowsAppsIcon.matches path then tr Strings.AppRules.windowsApps else pid.appName) + with _ -> None) + |> List.distinctBy(fun (path,_) -> path.ToUpperInvariant()) |> List.sortBy snd + +module CommonIconDrawing = + let glyph key = + TabIconChoices.common |> List.tryPick(fun (id,_,code,_) -> if id=key then Some code else None) + |> Option.defaultValue 0xE734 + /// Fill enclosed areas of the system glyph without changing its outer silhouette. + let drawAt (g:Graphics) (color:Color) key side = + use source = new Bitmap(128,128,PixelFormat.Format32bppArgb) + use ink = Graphics.FromImage source + if UiFace.glyph ink (glyph key) (RectangleF(4.0f,4.0f,120.0f,120.0f)) color then + let outside = Array.zeroCreate (128*128) + let queue = Collections.Generic.Queue() + let visit x y = + if x>=0 && y>=0 && x<128 && y<128 then + let index = y*128+x + if not outside.[index] && source.GetPixel(x,y).A<128uy then + outside.[index] <- true + queue.Enqueue index + for n in 0..127 do + visit n 0; visit n 127; visit 0 n; visit 127 n + while queue.Count>0 do + let index = queue.Dequeue() + let x,y = index%128,index/128 + visit (x-1) y; visit (x+1) y; visit x (y-1); visit x (y+1) + for y in 0..127 do + for x in 0..127 do + if not outside.[y*128+x] then source.SetPixel(x,y,color) + // Preserve the few interior cues that distinguish a controller and a globe. + if key="builtin:game" || key="builtin:globe" then + ink.CompositingMode <- Drawing2D.CompositingMode.SourceCopy + use clear = new SolidBrush(Color.Transparent) + if key="builtin:game" then + ink.FillRectangle(clear,30,47,10,34) + ink.FillRectangle(clear,18,59,34,10) + ink.FillEllipse(clear,84,45,13,13) + ink.FillEllipse(clear,99,65,13,13) + else + use meridian = new Pen(Color.Transparent,7.0f) + ink.SmoothingMode <- Drawing2D.SmoothingMode.AntiAlias + ink.DrawEllipse(meridian,42,12,44,104) + ink.FillRectangle(clear,12,60,104,8) + let state = g.Save() + g.InterpolationMode <- Drawing2D.InterpolationMode.HighQualityBicubic + g.DrawImage(source,Rectangle(0,0,side,side)) + g.Restore state + else g.DrawIcon(SystemIcons.Application,Rectangle(0,0,side,side)) + let draw g color key = drawAt g color key 128 + +module GroupIconFile = + /// Menu images arrive at different native sizes; normalize before WinForms measures rows. + let menuBitmap side (icon:Icon) = + let bitmap = new Bitmap(side,side,PixelFormat.Format32bppArgb) + try + use source = icon.ToBitmap() + use graphics = Graphics.FromImage bitmap + graphics.InterpolationMode <- Drawing2D.InterpolationMode.HighQualityBicubic + graphics.PixelOffsetMode <- Drawing2D.PixelOffsetMode.HighQuality + graphics.DrawImage(source,Rectangle(0,0,side,side)) + bitmap + with _ -> bitmap.Dispose(); reraise() + + let contrastColor (background:Color) (color:Color) = + let luminance (value:Color) = + let channel n = let v = float n/255.0 in if v<=0.04045 then v/12.92 else ((v+0.055)/1.055)**2.4 + 0.2126*channel value.R+0.7152*channel value.G+0.0722*channel value.B + let bg = luminance background + let target = if bg<0.179 then 255 else 0 + [0..100] |> List.map(fun step -> + let blend n = int(Math.Round(float n+(float target-float n)*float step/100.0)) + Color.FromArgb(blend color.R,blend color.G,blend color.B)) + |> List.find(fun value -> let fg = luminance value in (max bg fg+0.05)/(min bg fg+0.05)>=4.5) + + /// Keep the sidebar's glyphs, with each preset's hue adapted to the menu surface. + let menuBitmapOn side icon path background = + match TabIconChoices.common |> List.tryFind(fun (key,_,_,_) -> key=path) with + | Some(_,_,_,color) -> + let foreground = if SystemInformation.HighContrast then SystemColors.MenuText else contrastColor background color + let bitmap = new Bitmap(side,side,PixelFormat.Format32bppArgb) + try + use graphics = Graphics.FromImage bitmap + CommonIconDrawing.drawAt graphics foreground path side + bitmap + with _ -> bitmap.Dispose(); reraise() + | None -> menuBitmap side icon + + let private pictures = set [".png";".jpg";".jpeg";".bmp";".gif"] + /// An icon that owns its own copy of the bitmap's handle. + let private fromBitmap (bitmap:Bitmap) = + let handle = bitmap.GetHicon() + try (Icon.FromHandle(handle).Clone() :?> Icon) finally WinUserApi.DestroyIcon(handle) |> ignore + /// An .ico, a picture (square and whole, centred), or a program's or library's icon; None when + /// the file is gone or unreadable. + let load (path:string) : Icon option = + try + let builtin = TabIconChoices.builtins |> List.tryFind(fun (key,_,_) -> key=path) + if builtin.IsSome then let _,_,icon = builtin.Value in Some(icon.Clone() :?> Icon) + elif TabIconChoices.shell |> List.exists(fun (key,_,_) -> key=path) then + let _,_,id = TabIconChoices.shell |> List.find(fun (key,_,_) -> key=path) + AppIcons.GetStockIcon id |> Option.ofObj + elif TabIconChoices.common |> List.exists(fun (key,_,_,_) -> key=path) then + let _,_,_,color = TabIconChoices.common |> List.find(fun (key,_,_,_) -> key=path) + use bitmap = new Bitmap(128,128,PixelFormat.Format32bppArgb) + use graphics = Graphics.FromImage bitmap + CommonIconDrawing.draw graphics color path + Some(fromBitmap bitmap) + elif WindowsAppsIcon.matches path then + use bitmap = WindowsAppsIcon.image 64 + Some(fromBitmap bitmap) + elif not (IO.File.Exists path) then None + else + match IO.Path.GetExtension(path).ToLowerInvariant() with + | ".ico" -> Some(new Icon(path,Size(64,64))) + | extension when pictures.Contains extension -> + use source = new Bitmap(path) + let side = 128 + use square = new Bitmap(side,side,PixelFormat.Format32bppArgb) + do + use g = Graphics.FromImage(square) + g.InterpolationMode <- Drawing2D.InterpolationMode.HighQualityBicubic + let scale = float side/float (max source.Width source.Height) + let width,height = max 1 (int(float source.Width*scale)),max 1 (int(float source.Height*scale)) + g.DrawImage(source,Rectangle((side-width)/2,(side-height)/2,width,height)) + Some(fromBitmap square) + | _ -> + match AppIcons.GetFileIcon(path,64) with + | null -> Icon.ExtractAssociatedIcon(path) |> Option.ofObj + | bitmap -> + use shell = bitmap + Some(fromBitmap shell) + with _ -> None + +/// Weak keys let group-owned custom icons carry their borrowed app badge without extending either lifetime. +module TabIconImage = + let private badges = Runtime.CompilerServices.ConditionalWeakTable() + let attach icon original = badges.Add(icon,original) + let overhang icon side = if badges.TryGetValue(icon) |> fst then max 1 (side*3/13) else 0 + let draw (graphics:Graphics) (icon:Icon) (bounds:Rectangle) = + graphics.DrawIcon(icon,bounds) + match badges.TryGetValue icon with + | true,original -> + let side = max 1 (bounds.Width*10/13) + let extra = overhang icon bounds.Width + graphics.DrawIcon(original,Rectangle(bounds.Right+extra-side,bounds.Bottom+extra-side,side,side)) + | _ -> () + +/// Each group owns its custom icons; the original cache keeps ownership of app icons. +type TabIconCache() = + let icons = Collections.Generic.Dictionary() + member _.remove hwnd = + match icons.TryGetValue hwnd with + | true,(_,_,icon) -> icons.Remove hwnd |> ignore; icon |> Option.iter(fun owned -> owned.Dispose()) + | _ -> () + member this.get(hwnd,path:string option,original:Icon) = + match path with + | None -> this.remove hwnd; original + | Some path -> + match icons.TryGetValue hwnd with + | true,(saved,source,icon) when saved=path && obj.ReferenceEquals(source,original) -> icon |> Option.defaultValue original + | _ -> + this.remove hwnd + match GroupIconFile.load path with + | None -> icons.[hwnd] <- path,original,None; original + | Some custom -> + use custom = custom + let icon = custom.Clone() :?> Icon + TabIconImage.attach icon original + icons.[hwnd] <- path,original,Some icon + icon + interface IDisposable with + member _.Dispose() = + for _,_,icon in icons.Values do icon |> Option.iter(fun owned -> owned.Dispose()) + icons.Clear() + +module TabIconPicker = + let chooseFor title owner apply = + use dialog = new OpenFileDialog(Title=tr title,Filter=Localization.plain Strings.TabMenu.taskbarIconFiles,CheckFileExists=true) + if dialog.ShowDialog(owner)=DialogResult.OK then + match GroupIconFile.load dialog.FileName with + | Some icon -> icon.Dispose(); apply (Some dialog.FileName) + | None -> Alert.show AlertKind.Error (tr title) (tr Strings.TabMenu.invalidTabIcon) + + let choose owner apply = chooseFor Strings.TabMenu.changeTabIcon owner apply diff --git a/WtProgram/TabStripDecorator.fs b/WtProgram/TabStripDecorator.fs index fe6a7d86..cf2f30bf 100755 --- a/WtProgram/TabStripDecorator.fs +++ b/WtProgram/TabStripDecorator.fs @@ -572,6 +572,15 @@ type TabStripDecorator(group:WindowGroup) as this = let exeName = pid.exeName let processPath = pid.processPath + let pinned = PinnedTabs.contains hwnd + let pinTabItem = + CmiRegular({ + text = tr (if pinned then Strings.Commands.unpinTab.caption else Strings.Commands.pinTab.caption) + image = None + click = fun() -> group.setTabPinned(hwnd, not pinned) + flags = List2() + }) + let windowBehaviorMenu = let item label enabled command = CmiRegular({ text=tr label; image=None; click=(fun () -> group.run command) @@ -713,23 +722,6 @@ type TabStripDecorator(group:WindowGroup) as this = // Only a group with combined icons has a taskbar button of its own to change. let customIcon = if group.isSuperBarEnabled then Services.program.groupIcon hwnd else None - let changeIconItem = - CmiRegular({ - text = tr Strings.TabMenu.changeTaskbarIcon - image = None - flags = List2() - click = fun() -> - use dialog = new OpenFileDialog(Title=tr Strings.TabMenu.changeTaskbarIcon,Filter=Localization.plain Strings.TabMenu.taskbarIconFiles,CheckFileExists=true) - let owner = {new IWin32Window with member _.Handle=group.hwnd} - if dialog.ShowDialog(owner)=DialogResult.OK then Services.program.setGroupIcon(hwnd,Some dialog.FileName) - }) - let restoreIconItem = - CmiRegular({ - text = tr Strings.TabMenu.restoreTaskbarIcon - image = None - flags = List2() - click = fun() -> Services.program.setGroupIcon(hwnd,None) - }) let renameTabItem = CmiRegular({ text = tr Strings.TabMenu.renameTab @@ -795,15 +787,6 @@ type TabStripDecorator(group:WindowGroup) as this = click = fun() -> group.setTabName(hwnd, None) flags = List2() }) - let pinned = PinnedTabs.contains hwnd - let pinTabItem = - CmiRegular({ - text = tr (if pinned then Strings.Commands.unpinTab.caption else Strings.Commands.pinTab.caption) - image = None - click = fun() -> group.setTabPinned(hwnd, not pinned) - flags = List2() - }) - let isTabbingEnabled = Services.filter.getIsTabbingEnabledForProcess processPath let enableTabsItem = CmiRegular({ @@ -879,7 +862,7 @@ type TabStripDecorator(group:WindowGroup) as this = // the app's (in a group of several apps) and all. let closeMenu = CmiPopUp({text=tr Strings.TabMenu.close;image=None - items=List2([ Some closeTabItem; Some closeOtherTabsItem; Some closeTabsAfterItem + items=List2([ Some closeOtherTabsItem; Some closeTabsAfterItem (if mixesApps then Some closeAllExeTabsItem else None); Some closeAllTabsItem ] |> List.choose id)}) let managerItem = @@ -890,14 +873,38 @@ type TabStripDecorator(group:WindowGroup) as this = flags = List2() }) + let makeIconMenu title restore currentIcon apply = + let iconItem (path,label) = + let image = GroupIconFile.load path |> Option.map(fun icon -> + use icon = icon + let image = Img(GroupIconFile.menuBitmapOn (Dpi.scale 16) icon path (SettingsColors.current().surface)) + images.Add(image) + image) + CmiRegular({text=(if currentIcon=Some path then label+" ("+tr Strings.TabMenu.currentIcon+")" else label);image=image;flags=List2() + click=fun() -> apply (Some path)}) + let iconSection label choices = + if List.isEmpty choices then None else + Some(CmiPopUp({text=tr label;image=None;items=List2(List.map iconItem choices)})) + CmiPopUp({text=tr title;image=None;items=List2([ + iconSection Strings.TabMenu.systemTabIcons (TabIconChoices.windows |> List.map(fun (path,label) -> path,tr label)) + iconSection Strings.TabMenu.commonTabIcons (TabIconChoices.common |> List.map(fun (path,label,_,_) -> path,tr label)) + iconSection Strings.TabMenu.appTabIcons (TabIconChoices.applications()) + iconSection Strings.TabMenu.recentTabIcons (TabIconChoices.recent Services.settings.root |> List.filter IO.File.Exists |> List.map(fun path -> path,IO.Path.GetFileName path)) + Some CmiSeparator + Some(CmiRegular({text=tr Strings.TabMenu.chooseTabIconFile;image=None;flags=List2();click=fun() -> + TabIconPicker.chooseFor title {new IWin32Window with member _.Handle=group.hwnd} apply})) + Some(CmiRegular({text=tr restore;image=None;flags=List2();click=fun() -> apply None})) + ] |> List.choose id)}) + + let iconMenu = makeIconMenu Strings.TabMenu.tabIcon Strings.TabMenu.restoreTabIcon + (Services.program.getTabIcon hwnd) (fun path -> group.setTabIcon(hwnd,path)) + List2([ Some(newTabItem) Some(renameTabItem) (if group.isRenamed(hwnd) then Some(restoreTabNameItem) else None) - Some(pinTabItem) - Some(CmiRegular({ text=tr Strings.TabMenu.groupTopmost; image=None; flags=checkedFlag group.alwaysOnTop - click=fun () -> group.run ToggleGroupTopmost })) Some(colorMenu) + Some(iconMenu) Some(splitMenu) Some(CmiSeparator) Some(positionItem) @@ -905,14 +912,19 @@ type TabStripDecorator(group:WindowGroup) as this = Some(autoHideItem) Some(iconOnlyItem) Some(CmiSeparator) + Some(pinTabItem) + Some(CmiRegular({ text=tr Strings.TabMenu.groupTopmost; image=None; flags=checkedFlag group.alwaysOnTop + click=fun () -> group.run ToggleGroupTopmost })) Some(windowBehaviorMenu) Some(CmiSeparator) Some(sortTabsItem) Some(combineIconsInTaskbar) combineBlockedItem - (if group.isSuperBarEnabled then Some(changeIconItem) else None) - (if customIcon.IsSome then Some(restoreIconItem) else None) + (if group.isSuperBarEnabled then + Some(makeIconMenu Strings.TabMenu.taskbarIcon Strings.TabMenu.restoreTaskbarIcon customIcon + (fun path -> Services.program.setGroupIcon(hwnd,path))) else None) Some(CmiSeparator) + Some(closeTabItem) Some(closeMenu) // Named after the program itself, since these choices apply to all its windows. Some(CmiSection(pid.appName)) diff --git a/WtProgram/TabStripSprite.fs b/WtProgram/TabStripSprite.fs index d6a5e97f..e41f0e68 100644 --- a/WtProgram/TabStripSprite.fs +++ b/WtProgram/TabStripSprite.fs @@ -168,16 +168,17 @@ type IconSprite = { interface ISprite with member this.image = let pad = this.padding - let bitmap = Img(Sz(this.size.width+2*pad,this.size.height+2*pad)) + let extra = TabIconImage.overhang this.icon (min this.size.width this.size.height) + let bitmap = Img(Sz(this.size.width+2*pad+extra,this.size.height+2*pad+extra)) use g = bitmap.graphics try // WM_GETICON can return a 32/40px icon even for ICON_SMALL. // Scale the whole icon; drawing at its native size clips it. let bounds = Rectangle(pad,pad,this.size.width,this.size.height) - if this.opacity>=1.0f && not this.rim then g.DrawIcon(this.icon,bounds) + if this.opacity>=1.0f && not this.rim then TabIconImage.draw g this.icon bounds else - use source = new Bitmap(this.size.width+2*pad,this.size.height+2*pad,PixelFormat.Format32bppArgb) - using (Graphics.FromImage(source)) (fun ink -> ink.DrawIcon(this.icon,bounds)) + use source = new Bitmap(this.size.width+2*pad+extra,this.size.height+2*pad+extra,PixelFormat.Format32bppArgb) + using (Graphics.FromImage(source)) (fun ink -> TabIconImage.draw ink this.icon bounds) if this.rim then IconRim.add source (min this.size.width this.size.height) let bounds = Rectangle(0,0,source.Width,source.Height) use attributes = new System.Drawing.Imaging.ImageAttributes() diff --git a/WtProgram/WindowCustomizations.fs b/WtProgram/WindowCustomizations.fs index 92cfea96..7d83011d 100644 --- a/WtProgram/WindowCustomizations.fs +++ b/WtProgram/WindowCustomizations.fs @@ -26,7 +26,8 @@ module WindowCustomizations = if identify hwnd<>Some expected then None else let name = item.["name"] |> Option.ofObj |> Option.map(fun value -> value.Value()) |> Option.filter(String.IsNullOrEmpty >> not) let color = item.["color"] |> Option.ofObj |> Option.bind(fun value -> Theme.parseTabColor(value.Value())) - if name.IsNone && color.IsNone then None else Some(hwnd,name,color) + let icon = item.["icon"] |> Option.ofObj |> Option.map(fun value -> value.Value()) |> Option.filter(String.IsNullOrWhiteSpace >> not) + if name.IsNone && color.IsNone && icon.IsNone then None else Some(hwnd,name,color,icon) with _ -> None let read identify (root:JObject) = @@ -56,11 +57,12 @@ module WindowCustomizations = root.["windowCustomizations"] <- JArray(kept) true - let write identify (entries:(IntPtr * string option * TabColorChoice option) list) = - JArray(entries |> List.choose(fun (hwnd,name,color) -> - if name.IsNone && color.IsNone then None else + let write identify (entries:(IntPtr * string option * TabColorChoice option * string option) list) = + JArray(entries |> List.choose(fun (hwnd,name,color,icon) -> + if name.IsNone && color.IsNone && icon.IsNone then None else identify hwnd |> Option.map(fun (pid,started,stamp) -> let entry = JObject(JProperty("hwnd",hwnd.ToInt64()),JProperty("pid",pid),JProperty("started",started),JProperty("stamp",stamp)) name |> Option.iter(fun value -> entry.Add("name",JValue(value))) color |> Option.iter(fun value -> entry.Add("color",JValue(Theme.formatTabColor value))) + icon |> Option.iter(fun value -> entry.Add("icon",JValue(value))) entry))) diff --git a/WtProgram/WindowGroup.fs b/WtProgram/WindowGroup.fs index f36bcd5b..74a342ce 100755 --- a/WtProgram/WindowGroup.fs +++ b/WtProgram/WindowGroup.fs @@ -819,6 +819,7 @@ type WindowGroup(enableSuperBar:bool, plugins:List2, initialAppearance: /// which a refreshed tab's own minimize and maximize are not the group's to follow. let staleFrames = Collections.Generic.HashSet() let refreshing = Collections.Generic.Dictionary() + let tabIconCache = new TabIconCache() let iconCache = new WindowIconCache(invoker :> IDispatcher,fun hwnd -> Cell.beginUpdate() try @@ -1327,7 +1328,7 @@ type WindowGroup(enableSuperBar:bool, plugins:List2, initialAppearance: isRenamed = this.isRenamed hwnd splitTrail = SplitView.trail hwnd groupLayout isPinned = PinnedTabs.contains hwnd - iconSmall = small + iconSmall = tabIconCache.get(hwnd,Services.program.getTabIcon hwnd,small) iconBig = big // Called off the group's thread too: the tab in front is read from a field, not a cell. preview = fun() -> preview None @@ -2410,6 +2411,7 @@ type WindowGroup(enableSuperBar:bool, plugins:List2, initialAppearance: if not isDestroyed.value then match command with | ResetTabName hwnd -> if this.windows.contains hwnd then this.setTabName(hwnd,None) + | SetTabIcon(hwnd,path) -> if this.windows.contains hwnd then this.setTabIcon(hwnd,path) | SetTabColor(hwnd,color) -> if this.windows.contains hwnd then this.setTabColor(hwnd,color) | SetTabPinned(hwnd,pinned) -> if this.windows.contains hwnd then this.setTabPinned(hwnd,pinned) | MoveTab(hwnd,places) -> @@ -2673,6 +2675,11 @@ type WindowGroup(enableSuperBar:bool, plugins:List2, initialAppearance: member this.isPlacementIdle = FollowerPlacement.queue.isIdle(placementOwner) && not reconcileMinimizeState && not reconcilePlacementState && not splitPending && not emptyReveal + member this.setTabIcon(hwnd,path) = + Services.program.setTabIcon(hwnd,path) + tabIconCache.remove hwnd + this.setTabInfo(hwnd) + member this.setTabColor(hwnd,color) = Services.program.setTabColorOverride(hwnd,color) this.refreshTabColor(hwnd) @@ -3102,6 +3109,7 @@ type WindowGroup(enableSuperBar:bool, plugins:List2, initialAppearance: removedEvent.Trigger(hwnd) pendingMinimizeStates.Remove(hwnd) |> ignore requestedMinimizeStates.Remove(hwnd) |> ignore + tabIconCache.remove hwnd iconCache.remove(hwnd) // The successor, not the current foreground: Windows may still show the tab it // activated itself while our selection is on its way. @@ -3241,6 +3249,7 @@ type WindowGroup(enableSuperBar:bool, plugins:List2, initialAppearance: winEventHandler.value.iter <| fun d -> d.Dispose() this.windows.items.iter this.releaseGroupTopmost exitedEvent.Trigger() + (tabIconCache :> IDisposable).Dispose() (iconCache :> IDisposable).Dispose() (invoker :> IDisposable).Dispose() diff --git a/WtProgram/WtProgram.fsproj b/WtProgram/WtProgram.fsproj index 22e4bc3d..7d13509d 100755 --- a/WtProgram/WtProgram.fsproj +++ b/WtProgram/WtProgram.fsproj @@ -78,6 +78,7 @@ + diff --git a/docs/architecture.md b/docs/architecture.md index ce553b19..99d63ea0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -701,3 +701,17 @@ While a themed menu is open, its group STA owns a low-level mouse hook so clicks in other processes dismiss it too. The hook posts dismissal to the menu thread, always passes input through, and is removed on close or disposal. Hit testing includes visible submenus and their rounded regions. + +Custom tab icons use the same window lifetime validation and persistence as names +and colours. The main STA publishes immutable path snapshots; each group owns its +custom icons and disposes them when replaced, removed, or shut down. The custom +picture keeps its full size; the renderer adds the original app icon as a bottom-right +badge with its own overflow space. File loading is shared +with taskbar icons; missing files fall back to the original. The tab menu and command +palette share the picker and group command, including restoring the original icon. +The taskbar icon picker uses the same categories and file validation. Stable `builtin:` +IDs select Windows stock icons or coloured system-font symbols; file paths select +custom images. `recentTabIcons` retains ten case-insensitively unique file paths, +shared between tab and taskbar choices. Restoring an icon is an action; the selected +choice is labelled Current without covering its preview. Common menu symbols use +contrast-adjusted colours, or the system menu foreground in high contrast. diff --git a/tests/Architecture.fsx b/tests/Architecture.fsx index ecbf7150..3041037a 100644 --- a/tests/Architecture.fsx +++ b/tests/Architecture.fsx @@ -241,6 +241,8 @@ let main() = member _.shutdown() = () member _.setWindowNameOverride _ = () member _.getWindowNameOverride _ = None + member _.getTabIcon _ = None + member _.setTabIcon(_,_) = () member _.getTabColorOverride _ = None member _.setTabColorOverride _ = () member _.getTabColor(_,_) = None diff --git a/tests/CommandPalette.fsx b/tests/CommandPalette.fsx index 4b63bf4e..fb87c909 100644 --- a/tests/CommandPalette.fsx +++ b/tests/CommandPalette.fsx @@ -68,6 +68,7 @@ let main() = let called (text:string) = calls |> Seq.contains text let names = ConcurrentDictionary() let tabColors = ConcurrentDictionary() + let tabIcons = ConcurrentDictionary() /// The colour the program keeps for the group, as a group made by hand would. let groupColor = ref (None : TabColorChoice option) let hotKeys = ConcurrentDictionary() @@ -86,6 +87,11 @@ let main() = | Some name -> names.[hwnd] <- name | None -> names.TryRemove(hwnd) |> ignore member _.getWindowNameOverride hwnd = match names.TryGetValue hwnd with | true,name -> Some name | _ -> None + member _.getTabIcon hwnd = match tabIcons.TryGetValue hwnd with | true,path -> Some path | _ -> None + member _.setTabIcon(hwnd,path) = + match path with + | Some path -> tabIcons.[hwnd] <- path + | None -> tabIcons.TryRemove(hwnd) |> ignore member _.getTabColorOverride hwnd = match tabColors.TryGetValue hwnd with | true,color -> Some color | _ -> None member _.setTabColorOverride((hwnd,color)) = match color with @@ -208,7 +214,7 @@ let main() = // Dimmed while there is no workspace to choose. let needsWorkspace = set ["restore-workspace-named";"delete-workspace"] // Open a system dialog and wait on the user: listed, but not run unattended. - let interactive = set ["custom-tab-color";"change-group-icon";"new-group"] + let interactive = set ["custom-tab-color";"change-group-icon";"change-tab-icon";"new-group"] for command in Commands.all do let withTab = command.enabled active let withNone = command.enabled IntPtr.Zero @@ -219,7 +225,7 @@ let main() = // These wait on the tab's colour or the group's combined taskbar button. if needsSplit.Contains command.id then note (not withTab) (sprintf "%s is offered before starting split view" command.id) - elif not (needsWorkspace.Contains command.id) && command.id<>"change-group-icon" && command.id<>"restore-group-icon" && command.id<>"remember-tab-color" && command.id<>"remember-group-color" then + elif not (needsWorkspace.Contains command.id) && command.id<>"change-group-icon" && command.id<>"restore-group-icon" && command.id<>"remember-tab-color" && command.id<>"remember-group-color" && command.id<>"restore-tab-icon" then note withTab (sprintf "%s is dimmed with a tab in front" command.id) for command in Commands.all do // Settings toggles are walked below, each turned and turned back. @@ -280,6 +286,33 @@ let main() = settle active note (not (tabColors.ContainsKey active)) "Clear tab color left the colour") commandsRun.Add "custom-tab-color" |> ignore + commandsRun.Add "change-tab-icon" |> ignore + attempt "tab-icon" (fun () -> + let options = choicesOf "tab-icon" active + note ((options |> List.find(fun item -> item.label=tr Strings.TabMenu.restoreTabIcon)).detail="") "Restore icon was shown as a checked state instead of an action" + note (options |> List.exists(fun item -> item.label=tr Strings.TabMenu.restoreTabIcon)) "The icon picker omitted restore" + match options.Head.run() with + | Choose icons -> + icons.Head.run() |> ignore + settle active + note (tabIcons.[active]="builtin:application") "Choosing a built-in icon did not update the tab" + let selected = choicesOf "tab-icon" active + match selected.Head.run() with + | Choose icons -> note (icons.Head.detail=tr Strings.TabMenu.currentIcon) "The selected icon did not use a text status" + | _ -> failwith "Missing icon choices" + options |> List.find(fun item -> item.label=tr Strings.TabMenu.restoreTabIcon) |> fun item -> item.run() |> ignore + settle active + | _ -> failwith "Built-in icons did not open a choice list") + attempt "restore-tab-icon" (fun () -> + note (not ((Commands.find "restore-tab-icon").Value.enabled active)) "Restore tab icon is offered without a custom icon" + let group = groups() |> List.find(fun group -> (group :> IGroup).windows.contains((=)active)) + (group :> IGroup).run(SetTabIcon(active,Some "missing-test-icon.png")) + settle active + note (tabIcons.ContainsKey active) "Setting a tab icon did not reach the owning service" + note ((Commands.find "restore-tab-icon").Value.enabled active) "Restore tab icon is dimmed with a custom icon" + runDone "restore-tab-icon" active + settle active + note (not (tabIcons.ContainsKey active)) "Restore tab icon left the override") attempt "move-tab-right" (fun () -> let before = lorderOf active |> List.findIndex ((=) active) runDone "move-tab-right" active @@ -545,6 +578,13 @@ let main() = pumpUntil "Combining the group's taskbar icons" (fun () -> groupOf active |> Option.exists(fun info -> info.isSuperBarEnabled)) note ((Commands.find "change-group-icon").Value.enabled active && (Commands.find "restore-group-icon").Value.enabled active) "The group's taskbar icon commands stay dimmed once its icons are combined" + let taskbarIcons = choicesOf "change-group-icon" active + note (taskbarIcons |> List.exists(fun item -> item.label=tr Strings.TabMenu.commonTabIcons)) "Taskbar picker omitted common icons" + note (taskbarIcons |> List.exists(fun item -> item.label=tr Strings.TabMenu.restoreTaskbarIcon && item.detail="")) "Taskbar picker omitted its restore action" + match taskbarIcons.Head.run() with + | Choose icons -> icons.Head.run() |> ignore + | _ -> failwith "Taskbar system icons were not selectable" + note (called (sprintf "setGroupIcon %A" (Some "builtin:application"))) "Taskbar picker did not apply the chosen icon" runDone "restore-group-icon" active note (called "setGroupIcon None") "Restore taskbar icon did not restore it" runDone "combine-group-taskbar-icons" active diff --git a/tests/GroupEditor.fsx b/tests/GroupEditor.fsx index 9b948972..2d9a2531 100644 --- a/tests/GroupEditor.fsx +++ b/tests/GroupEditor.fsx @@ -1239,6 +1239,8 @@ let main() = member _.shutdown() = () member _.setWindowNameOverride _ = () member _.getWindowNameOverride _ = None + member _.getTabIcon _ = None + member _.setTabIcon(_,_) = () member _.getTabColorOverride _ = None member _.setTabColorOverride _ = () member _.getTabColor(_,_) = None diff --git a/tests/GroupLifecycle.fsx b/tests/GroupLifecycle.fsx index 0e68f82f..34510b13 100644 --- a/tests/GroupLifecycle.fsx +++ b/tests/GroupLifecycle.fsx @@ -92,6 +92,8 @@ let main() = member _.shutdown() = () member _.setWindowNameOverride _ = () member _.getWindowNameOverride _ = None + member _.getTabIcon _ = None + member _.setTabIcon(_,_) = () member _.getTabColorOverride _ = None member _.setTabColorOverride _ = () member _.getTabColor(_,_) = None diff --git a/tests/GroupOperations.fsx b/tests/GroupOperations.fsx index 6e3aded8..833d65b5 100644 --- a/tests/GroupOperations.fsx +++ b/tests/GroupOperations.fsx @@ -474,6 +474,8 @@ let main() = member _.getWindowNameOverride hwnd = Threading.Interlocked.Increment(&nameReads.contents) |> ignore match names.TryGetValue(hwnd) with | true,name -> Some name | _ -> None + member _.getTabIcon _ = None + member _.setTabIcon(_,_) = () member _.getTabColorOverride _ = None member _.setTabColorOverride _ = () member _.getTabColor(_,_) = None @@ -1836,8 +1838,13 @@ let main() = let closeAllOf hwnd = Localization.tr (Strings.TabMenu.closeAllOf (OS().windowFromHwnd(hwnd).pid.exeName)) let alone = menuTexts handles.Head check (List.head alone = Localization.tr Strings.TabMenu.newTab + "\tCtrl+Alt+N") "The tab menu does not start with New tab and its shortcut" - // Closing is a submenu: the tab first, with its shortcut of its own, Ctrl+Alt+W. - check (List.head (closeTexts handles.Head) = Localization.tr Strings.Settings.closeTab.caption + "\tCtrl+Alt+W") "Close does not start with Close tab and its shortcut" + // The current tab is a direct action; bulk close operations stay in their submenu. + let closeTabText = Localization.tr Strings.Settings.closeTab.caption + "\tCtrl+Alt+W" + check (List.contains closeTabText alone && not(List.contains closeTabText (closeTexts handles.Head))) "Close tab was not moved to the top level with its shortcut" + check (List.head (closeTexts handles.Head)=Localization.tr Strings.TabMenu.closeOthers) "Bulk close menu does not start with Close others" + let restoreIcon = popupItems Strings.TabMenu.tabIcon handles.Head |> List.find(fun item -> item.text=Localization.tr Strings.TabMenu.restoreTabIcon) + check (not(List.contains MenuFlags.MF_CHECKED restoreIcon.flags.list)) "Restore icon is marked as a selected state" + check (not(List.contains (Localization.tr Strings.TabMenu.chooseTabIconFile) alone)) "The icon file picker leaked into the top-level menu" // Split view starts with the clicked tab's neighbour, needing no choice; it is // greyed only for a tab with no other tab to take. let splitFirst hwnd = onGroup(fun group -> diff --git a/tests/Reliability.fsx b/tests/Reliability.fsx index 962ea48b..b0a57f02 100644 --- a/tests/Reliability.fsx +++ b/tests/Reliability.fsx @@ -23,17 +23,101 @@ type SyncCallWindow(onMessage:unit -> unit) = if m.Msg = 0x8001 then onMessage() else base.WndProc(&m) let main() = + let history = JObject() + for n in 1..12 do TabIconChoices.remember (sprintf "C:/icons/%d.png" n) history + TabIconChoices.remember "c:/ICONS/12.png" history + TabIconChoices.remember "builtin:warning" history + let recent = TabIconChoices.recent history + check (recent.Length=10 && recent.Head="c:/ICONS/12.png") "Recent icons were not bounded and deduplicated" + for path,_,_ in TabIconChoices.builtins do + match GroupIconFile.load path with + | Some icon -> icon.Dispose() + | None -> failwith ("Built-in icon did not load: "+path) + check (TabIconChoices.windows.Length=12) "Windows icon list must contain twelve choices" + for path,_ in TabIconChoices.windows do + match GroupIconFile.load path with + | Some icon -> icon.Dispose() + | None -> failwith ("Windows icon failed: "+path) + for path,_,_,color in TabIconChoices.common do + match GroupIconFile.load path with + | Some icon -> + use icon = icon + use image = GroupIconFile.menuBitmap 16 icon + let pixels = [for y in 0..15 do for x in 0..15 do yield image.GetPixel(x,y)] + check ((pixels |> List.filter(fun pixel -> pixel.A>128uy) |> List.length)>=8) "System glyph rendered empty at menu size" + use full = icon.ToBitmap() + if path="builtin:star" || path="builtin:heart" then + check (full.GetPixel(64,64).A=255uy) "A filled system glyph retained its hollow centre" + if path="builtin:game" then + check (full.GetPixel(35,64).A=0uy && full.GetPixel(90,51).A=0uy && full.GetPixel(64,64).A>128uy) "Game controller lost its controls" + if path="builtin:globe" then + check (full.GetPixel(42,64).A=0uy && full.GetPixel(64,40).A>128uy && full.GetPixel(43,50).A<128uy) "Globe lost its curved meridian" + | None -> failwith ("Common icon failed to load: "+path) + use themeIcon = Drawing.SystemIcons.Application.Clone() :?> Drawing.Icon + for background in [Drawing.Color.White;Drawing.Color.FromArgb(40,40,40)] do + let foreground = GroupIconFile.contrastColor background Drawing.Color.Goldenrod + use image = GroupIconFile.menuBitmapOn 16 themeIcon "builtin:star" background + let ink = [for y in 0..15 do for x in 0..15 do let pixel = image.GetPixel(x,y) in if pixel.A=255uy then yield pixel] + check (not ink.IsEmpty && (ink |> List.filter(fun pixel -> abs(int pixel.R-int foreground.R)<=2 && abs(int pixel.G-int foreground.G)<=2 && abs(int pixel.B-int foreground.B)<=2) |> List.length)*2>=ink.Length) "System icon lost its theme-adapted preset colour" + check (foreground.R<>foreground.B) "The coloured system glyph became monochrome" + for side in [16;24;32] do + for native in [16;32;64] do + use icon = new Drawing.Icon(Drawing.SystemIcons.Application,Drawing.Size(native,native)) + use image = GroupIconFile.menuBitmap side icon + check (image.Width=side && image.Height=side) "Menu icon dimensions depended on the source icon size" + check (WindowsAppsIcon.matches "C:/Windows/System32/ApplicationFrameHost.exe") "Windows apps host was not recognized" + match GroupIconFile.load "C:/Windows/System32/ApplicationFrameHost.exe" with + | Some icon -> + use icon = icon + use bitmap = icon.ToBitmap() + check (bitmap.GetPixel(8,8).B=212uy && bitmap.GetPixel(31,31).A=0uy) "Windows apps picker icon differed from App Rules" + | None -> failwith "Windows apps icon did not load" let customWindow = IntPtr 123 let identity hwnd = if hwnd=customWindow then Some(42,100L,17L) else None - let custom = customWindow,Some "game",Some(PaletteColor 2) + let custom = customWindow,Some "game",Some(PaletteColor 2),Some "custom.png" let root = JObject(JProperty("windowCustomizations",WindowCustomizations.write identity [custom])) check (WindowCustomizations.read identity root=[custom]) "Window name and colour did not survive serialization" check ((WindowCustomizations.read (fun _ -> Some(42,101L,17L)) root).IsEmpty) "A reused process inherited a window's custom name or colour" check ((WindowCustomizations.read (fun _ -> None) root).IsEmpty) "A closed window's customizations were restored" check ((WindowCustomizations.read (fun _ -> Some(42,100L,18L)) root).IsEmpty) "A reused HWND inherited another window's customizations" - let cleared = JObject(JProperty("windowCustomizations",WindowCustomizations.write identity [customWindow,None,None])) + let cleared = JObject(JProperty("windowCustomizations",WindowCustomizations.write identity [customWindow,None,None,None])) check ((WindowCustomizations.read identity cleared).IsEmpty) "Resetting a name and colour left saved overrides" + let iconOnly = customWindow,None,None,Some "custom.png" + let iconRoot = JObject(JProperty("windowCustomizations",WindowCustomizations.write identity [iconOnly])) + check (WindowCustomizations.read identity iconRoot=[iconOnly]) "An icon-only customization was lost" + let legacy = JObject(JProperty("windowCustomizations",JArray(JObject(JProperty("hwnd",123),JProperty("pid",42),JProperty("started",100L),JProperty("stamp",17L),JProperty("name","legacy"))))) + check (WindowCustomizations.read identity legacy=[customWindow,Some "legacy",None,None]) "Old customizations without an icon stopped loading" + let picture = IO.Path.Combine(IO.Path.GetTempPath(),Guid.NewGuid().ToString()+".png") + try + use bitmap = new Drawing.Bitmap(64,64) + use graphics = Drawing.Graphics.FromImage bitmap + graphics.Clear Drawing.Color.Red + bitmap.Save(picture,Drawing.Imaging.ImageFormat.Png) + use originalBitmap = new Drawing.Bitmap(32,32) + use originalGraphics = Drawing.Graphics.FromImage originalBitmap + originalGraphics.Clear Drawing.Color.Blue + let handle = originalBitmap.GetHicon() + use original = try Drawing.Icon.FromHandle(handle).Clone() :?> Drawing.Icon finally WinUserApi.DestroyIcon(handle) |> ignore + use cache = new TabIconCache() + let custom = cache.get(customWindow,Some picture,original) + let render icon = + let image = new Drawing.Bitmap(80,80) + use ink = Drawing.Graphics.FromImage image + TabIconImage.draw ink icon (Drawing.Rectangle(0,0,64,64)) + image + use composed = render custom + check (composed.GetPixel(8,8).R>240uy && composed.GetPixel(56,56).B>240uy) "Custom tab icon lost its original bottom-right badge" + check (composed.GetPixel(24,24).R>240uy && composed.GetPixel(32,32).B>240uy && composed.GetPixel(60,8).R>240uy && composed.GetPixel(76,76).B>240uy) "The app badge did not project beyond the custom picture at the bottom right" + check (obj.ReferenceEquals(custom,cache.get(customWindow,Some picture,original))) "An unchanged tab icon was recreated" + check (obj.ReferenceEquals(original,cache.get(customWindow,None,original))) "Restoring a tab icon did not return its original" + check (obj.ReferenceEquals(original,cache.get(customWindow,Some(picture+".missing"),original))) "A missing custom icon did not fall back to the original" + use transferred = new TabIconCache() + use transferredImage = render (transferred.get(customWindow,Some picture,original)) + check (transferredImage.GetPixel(8,8).R>240uy && transferredImage.GetPixel(56,56).B>240uy) "A new group could not rebuild the custom icon" + finally + IO.File.Delete picture + let mixed = JObject(JProperty("windowCustomizations",JArray(root.["windowCustomizations"].[0].DeepClone(),JObject(JProperty("hwnd",999),JProperty("pid",42),JProperty("started",100L),JProperty("stamp",17L),JProperty("name","old"))))) let mutable identityCalls = 0 let restored,pending = WindowCustomizations.restore (fun hwnd -> identityCalls<-identityCalls+1;identity hwnd) mixed @@ -45,7 +129,7 @@ let main() = check (not(WindowCustomizations.cleanup mixed pending.Value)) "Startup cleanup overwrote a newer reset" // Compare the old restore-only scan with restore plus cleanup planning; JSON parsing and disk IO are outside this measurement. for count in [100;1000] do - let data = [1..count] |> List.map(fun n -> IntPtr n,Some "game",Some(PaletteColor 2)) + let data = [1..count] |> List.map(fun n -> IntPtr n,Some "game",Some(PaletteColor 2),None) let all _ = Some(42,100L,17L) let sample = JObject(JProperty("windowCustomizations",WindowCustomizations.write all data)) for stale in [false;true] do diff --git a/tests/RenderingPerf/SettingsWindow.fs b/tests/RenderingPerf/SettingsWindow.fs index 2da30541..1a150ec4 100644 --- a/tests/RenderingPerf/SettingsWindow.fs +++ b/tests/RenderingPerf/SettingsWindow.fs @@ -38,6 +38,8 @@ let run measure iterations (pixels:Bitmap -> string) (results:JArray) (images:JA member _.shutdown() = () member _.setWindowNameOverride _ = () member _.getWindowNameOverride _ = None + member _.getTabIcon _ = None + member _.setTabIcon(_,_) = () member _.getTabColorOverride _ = None member _.setTabColorOverride _ = () member _.getTabColor(_,_) = None diff --git a/tests/SettingsEditors.fsx b/tests/SettingsEditors.fsx index 7a233d35..504467e7 100644 --- a/tests/SettingsEditors.fsx +++ b/tests/SettingsEditors.fsx @@ -487,6 +487,8 @@ let main() = member _.shutdown() = () member _.setWindowNameOverride _ = () member _.getWindowNameOverride _ = None + member _.getTabIcon _ = None + member _.setTabIcon(_,_) = () member _.getTabColorOverride _ = None member _.setTabColorOverride _ = () member _.getTabColor(_,_) = None diff --git a/tests/SplitViewDesktop.fsx b/tests/SplitViewDesktop.fsx index 596bcbd8..5f5493c2 100644 --- a/tests/SplitViewDesktop.fsx +++ b/tests/SplitViewDesktop.fsx @@ -98,6 +98,8 @@ let main() = member _.shutdown() = () member _.setWindowNameOverride _ = () member _.getWindowNameOverride _ = None + member _.getTabIcon _ = None + member _.setTabIcon(_,_) = () member _.getTabColorOverride _ = None member _.setTabColorOverride _ = () member _.getTabColor(_,_) = None