拆分窗格gui对象

Ist*_*har 14 user-interface wolfram-mathematica

我一直在开发一个gui,这需要创建Mathematica缺少的公共控件(例如spinner,treeview,openerbar等).一个是多面板,即窗格对象,它被分成两个(或更多)子窗格,其中分隔符可以由鼠标设置.这是我的双窗格版本.我想听听你的意见和想法,关于如何扩展它以处理不仅仅是2个,而是处理任何数量的子窗格,以及如何优化它.目前,对于负载很重的子窗格,它严重滞后,不知道为什么.

Options[SplitPane] = {Direction -> "Vertical", 
   DividerWidth -> Automatic, Paneled -> {True, True}};
SplitPane[opts___?OptionQ] := 
  Module[{dummy}, SplitPane[Dynamic[dummy], opts]];
SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];
SplitPane[val_, content_, opts___?OptionQ] := 
  SplitPane[val, content, {100, 50}, opts];
SplitPane[Dynamic[split_, arg___], {expr1_, expr2_}, {maxX_, maxY_}, 
   opts___?OptionQ] := 
  DynamicModule[{temp, dir, d, panel, coord, max, fix, val},
   {dir, d, panel} = {Direction, DividerWidth, Paneled} /. {opts} /. 
     Options[SplitPane];
   dir = dir /. {Bottom | Top | "Vertical" -> "Vertical", _ -> 
       "Horizontal"};
   d = d /. Automatic -> 2;
   split = If[NumberQ[split], split, max/2];
   val = Clip[split /. {_?NumberQ -> split, _ -> maxX/2}, {0, maxX}];
   {coord, max, fix} = 
    Switch[dir, "Vertical", {First, maxX, maxY}, 
     "Horizontal", {(max - Last[#]) &, maxY, maxX}];
   panel = (# /. {None | False -> 
          Identity, _ -> (Panel[#, ImageMargins -> 0, 
             FrameMargins -> -1] &)}) & /@ panel;

   Grid[If[dir === "Vertical",
     {{
       Dynamic[
        panel[[1]]@
         Pane[expr1, ImageSize -> {split - d, fix}, 
          ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, 
          AppearanceElements -> None], TrackedSymbols :> {split}],
       Deploy@EventHandler[
         MouseAppearance[
          Pane[Null, ImageSize -> {d*2, fix}, ImageMargins -> -1, 
           FrameMargins -> -1], "FrameLRResize"],
         "MouseDown" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = 
            If[Abs[temp - split] <= d \[And] 0 <= temp <= max, temp, 
             split]), 
         "MouseDragged" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = If[0 <= temp <= max, temp, split])],
       Dynamic@
        panel[[2]]@
         Pane[expr2, ImageSizeAction -> "Scrollable", 
          Scrollbars -> Automatic, AppearanceElements -> None, 
          ImageSize -> {max - split - d, fix}]
       }},
     {
      List@
       Dynamic[panel[[1]]@
         Pane[expr1, ImageSize -> {fix, split - d}, 
          ImageSizeAction -> "Scrollable", Scrollbars -> Automatic, 
          AppearanceElements -> None], TrackedSymbols :> {split}],
      List@Deploy@EventHandler[
         MouseAppearance[
          Pane[Null, ImageSize -> {fix, d*2}, ImageMargins -> -1, 
           FrameMargins -> -1], "FrameTBResize"],
         "MouseDown" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = 
            If[Abs[temp - split] <= d \[And] 0 <= temp <= max, temp, 
             split]), 
         "MouseDragged" :> (temp = 
            coord@MousePosition@"CellContentsAbsolute"; 
           split = If[0 <= temp <= max, temp, split])],
      List@
       Dynamic[panel[[2]]@
         Pane[expr2, ImageSizeAction -> "Scrollable", 
          Scrollbars -> Automatic, 
          ImageSize -> {fix, max - split - d}, 
          AppearanceElements -> None], TrackedSymbols :> {split}]
      }
     ], Spacings -> {0, -.1}]
   ];
SplitPane[val_, arg___] /; NumberQ[val] := 
  Module[{x = val}, SplitPane[Dynamic[x], arg]];

pos = 300;
SplitPane[
 Dynamic[pos], {Manipulate[
   Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}], 
  Factorial[123]}, {500, 300}]
Run Code Online (Sandbox Code Playgroud)

SplitPane输出

Leo*_*rin 14

推广到几个面板的关键是重构代码.在目前的形式中,虽然非常好,但它将可视化/ UI原语和选项与分离逻辑混合在一起,并且具有大量重复的代码.这使得泛化变得困难.这是重构版本:

ClearAll[SplitPane];
Options[SplitPane] = {
    Direction -> "Vertical", DividerWidth -> Automatic, Paneled -> True
};
SplitPane[opts___?OptionQ] :=   Module[{dummy}, SplitPane[Dynamic[dummy], opts]];
SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];
SplitPane[val_, content_, opts___?OptionQ] :=
    SplitPane[val, content, {100, 50}, opts];
SplitPane[sp_List, {cont__}, {maxX_, maxY_}, opts___?OptionQ] /; 
        Length[sp] == Length[Hold[cont]] - 1 :=
  Module[{scrollablePane, dividerPane, onMouseDownCode, onMouseDraggedCode, dynPane,
      gridArg, split, divider, panel},
    With[{paneled = Paneled /. {opts} /. Options[SplitPane],len = Length[Hold[cont]]},
       Which[
          TrueQ[paneled ],
             panel = Table[True, {len}],
          MatchQ[paneled, {Repeated[(True | False), {len}]}],
             panel = paneled,
          True,
            Message[SplitPane::badopt]; Return[$Failed, Module]
       ]
    ];

    DynamicModule[{temp, dir, d, coord, max, fix, val},
      {dir, d} = {Direction, DividerWidth}/.{opts}/.Options[SplitPane];
      dir =  dir /. {
         Bottom | Top | "Vertical" -> "Vertical", _ -> "Horizontal"
      };
      d = d /. Automatic -> 2;
      val = Clip[sp /. {_?NumberQ -> sp, _ -> maxX/2}, {0, maxX}];
      {coord, max, fix} =
        Switch[dir,
          "Vertical",
             {First, maxX, maxY},
          "Horizontal",
             {(max - Last[#]) &, maxY, maxX}
        ];
      Do[split[i] = sp[[i]], {i, 1, Length[sp]}];
      split[Length[sp] + 1] = max - Total[sp] - 2*d*Length[sp];
      panel =
          (# /. {
            None | False -> Identity, 
            _ -> (Panel[#, ImageMargins -> 0,FrameMargins -> -1] &)
           }) & /@ panel;
      scrollablePane[args___] :=
          Pane[args, ImageSizeAction -> "Scrollable", 
               Scrollbars -> Automatic, AppearanceElements -> None];
      dividerPane[size : {_, _}] :=
          Pane[Null, ImageSize -> size, ImageMargins -> -1,FrameMargins -> -1];

      onMouseDownCode[n_] := 
        Module[{old},
          temp = coord@MousePosition@"CellContentsAbsolute";
          If[Abs[temp - split[n]] <= d \[And] 0 <= temp <= max,
            old = split[n];
            split[n] = temp-Sum[split[i], {i, n - 1}];
            split[n + 1] += old - split[n];       
        ]];

      onMouseDraggedCode[n_] :=
         Module[{old},
            temp = coord@MousePosition@"CellContentsAbsolute";
            If[0 <= temp <= max,
               old = split[n];
               split[n] = temp -Sum[split[i], {i, n - 1}];
               split[n + 1] += old - split[n];
            ] ;
         ];

      SetAttributes[dynPane, HoldFirst];
      dynPane[expr_, n_, size_] :=
          panel[[n]]@scrollablePane[expr, ImageSize -> size];

      divider[n_, sizediv_, resizeType_] :=
         Deploy@EventHandler[
            MouseAppearance[dividerPane[sizediv], resizeType],
           "MouseDown" :> onMouseDownCode[n],
           "MouseDragged" :> onMouseDraggedCode[n]
         ];

      SetAttributes[gridArg, HoldAll];
      gridArg[{content__}, sizediv_, resizeType_, sizeF_] :=
         Module[{myHold, len = Length[Hold[content]] },
           SetAttributes[myHold, HoldAll];
           List @@ Map[
             Dynamic,
             Apply[Hold, 
                MapThread[Compose,
                   {
                      Range[len] /. {
                        len :>               
                          Function[
                             exp, 
                             myHold[dynPane[exp, len, sizeF[len]]], 
                             HoldAll
                          ],
                        n_Integer :>
                          Function[exp,
                             myHold[dynPane[exp, n, sizeF[n]],
                                divider[n, sizediv, resizeType]
                             ], 
                          HoldAll]
                      },
                      Unevaluated /@ Unevaluated[{content}]
                    }] (* MapThread *)
               ] /. myHold[x__] :> x
           ] (* Map *)
         ]; (* Module *)
      (* Output *)
      Grid[
        If[dir === "Vertical",
           List@ gridArg[{cont}, {d*2, fix},"FrameLRResize",{split[#] - d, fix} &],
           (* else *)
           List /@ gridArg[{cont}, {fix, d*2},"FrameTBResize", {fix, split[#] - d} &]
        ],
        Spacings -> {0, -.1}]]];

SplitPane[val_, arg___] /; NumberQ[val] := 
   Module[{x = val}, SplitPane[Dynamic[x], arg]];
Run Code Online (Sandbox Code Playgroud)

以下是它的外观:

SplitPane[{300, 300}, 
 {
   Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}], 
   Factorial[123], 
   CompleteGraph[5]
 }, {900, 300}]
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

无法评论您提到的性能问题.此外,当您开始使用鼠标拖动时,实际光标位置通常相对于分隔符位置非常偏离.这适用于您和我的版本,也许需要一些更精确的缩放.

只想再次强调 - 只有在我进行重构之后才能实现泛化,将分裂逻辑与可视化相关的事物分开.至于优化,我也认为,出于同样的原因,尝试优化此版本比原始版本更容易.

编辑

我有点犹豫要添加这个注释,但必须提到的是,我的上述解决方案在工作时,显示了一个被专家UI mma程序员认为不好的做法.即,它使用Module-产生内部变量Dynamic内于Module(特别地,split在上面的代码中,还有各种辅助功能).我使用它的原因是我无法仅使用DynamicModule- 生成的变量,以及Module- 生成的变量之前始终适用于我.但是,请参阅John Fultz在这个 MathGroup主题中的帖子,其中他声明应该避免这种做法.

  • 干得好.顺便说一下,鼠标位置相对于分隔符位置关闭的原因是因为在`onMouseDraggedCode [n_]`中,`temp`是分隔符`n`相对于左侧的新位置(cq top )但是`split [n]`存储分隔符相对于其直接邻居的位置.这意味着`split [n]`应该设置为`split [n] = temp-Sum [split [i],{i,n-1}]`. (2认同)

Ist*_*har 6

在Leonid的解决方案上大量建立,这是我的版本.我已经应用了几个更改,基本上是为了更容易跟踪动态大小更改,因为我只是无法内化Leonid代码的一部分.

做出的改变:

  • 删除DividerWidth选项,现在无法由用户设置.这并不重要.
  • 最大水平尺寸(maxX在上面的帖子中)被删除,因为它现在是根据用户指定的面板宽度值计算的:w.
  • 第一个参数(w主动态变量)明确保存面板的宽度,而不是保存分隔符位置.此外,它被设为list(w[[n]])而不是函数(就像split[n]Leonid的版本一样).
  • 为分隔符添加了最小化/恢复按钮.
  • 限制分隔器移动:分隔器只能从左侧移动到右侧移动,无法进一步移动.
  • 微调分频器宽度,ImageMargins,FrameMargins,Spacings以允许零大小的窗格.

仍有待解决的问题:

  • 当最小化/最大化分频器时,它们应该重叠左/右分频器.LIFO叠加器可以解决将分频器设置为最大值的问题,而不是尝试通过按钮更改其他分频器.这可能会导致一些问题,因为它们会回到以前的状态.堆叠分隔器的问题在于它无法在网格中解决,或者只能通过非常专门调整的负空间来解决.我认为这不值得处理.
  • 将面板缩小到零宽度/高度时出现轻微对齐问题.这个我可以忍受.

ClearAll[SplitPane];
Options[SplitPane] = {Direction -> "Vertical", Paneled -> True};
SplitPane[opts___?OptionQ] := 
  Module[{dummy = {200, 200}}, SplitPane[Dynamic[dummy], opts]];
SplitPane[val_, opts___?OptionQ] := SplitPane[val, {"", ""}, opts];
SplitPane[val_, content_, opts___?OptionQ] := 
  SplitPane[val, content, Automatic, opts];
SplitPane[Dynamic[w_], cont_, s_, opts___?OptionQ] :=
  DynamicModule[{
    scrollPane, divPane, onMouseDownCode, onMouseDraggedCode, grid,
    dir, panel, bg, coord, mouse, icon, sizeD, sizeB,
    num, old, pos, origo, temp, max, prev, state, fix},

   {dir, panel} = {Direction, Paneled} /. {opts} /. Options@SplitPane;
   dir = dir /. {Bottom | Top | "Vertical" -> "Vertical", _ -> 
       "Horizontal"};
   bg = panel /. {None | False -> GrayLevel@.9, _ -> None};
   panel = 
    panel /. {None | False -> 
       None, _ -> {RGBColor[0.70588, 0.70588, 0.70588]}}; (* 
   Simulate Panel-like colors on the frame. *)
   fix = s /. {Automatic -> If[dir === "Vertical", 300, 800]};

   (* {coordinate function, mouse cursor, button icon, divider size, 
   button size} *)
   {coord, mouse, icon, sizeD, sizeB} = Switch[dir,
     "Vertical", {First, 
      "FrameLRResize", {"\[RightPointer]", "\[LeftPointer]"}, {5, 
       fix}, {5, 60}},
     "Horizontal", {(max - Last@#) &, 
      "FrameTBResize", {"\[DownPointer]", "\[UpPointer]"}, {fix, 
       7}, {60, 7}}
     ];

   SetAttributes[{scrollPane, grid}, HoldAll];
   (* Framed is required below becase otherwise the horizontal \
version of scrollPane cannot be set to zero height. *)
   scrollPane[expr_, size_] := 
    Framed[Pane[expr, Scrollbars -> Automatic, 
      AppearanceElements -> None, ImageSizeAction -> "Scrollable", 
      ImageMargins -> 0, FrameMargins -> 0, ImageSize -> size], 
     FrameStyle -> panel, ImageMargins -> 0, FrameMargins -> 0, 
     ImageSize -> size];
   divPane[n_] :=
    Deploy@EventHandler[MouseAppearance[Framed[
        Item[Button[Dynamic@If[state[[n]], First@icon, Last@icon],

          If[state[[n]], prev[[n]] = w; 
           w[[n]] = max - Sum[w[[i]], {i, n - 1}]; 
           Do[w[[i]] = 0, {i, n + 1, num}]; state[[n]] = False;, 
           w = prev[[n]]; state[[n]] = True;]
          , ContentPadding -> False, ImageSize -> sizeB, 
          FrameMargins -> 0, ImageMargins -> -1, 
          Appearance -> "Palette"], Alignment -> {Center, Center}]
        , ImageSize -> sizeD, FrameStyle -> None, ImageMargins -> 0, 
        FrameMargins -> 0, Background -> bg], mouse], 
      "MouseDown" :> onMouseDownCode@n, 
      "MouseDragged" :> onMouseDraggedCode@n, PassEventsDown -> True];
   onMouseDownCode[n_] := (
     old = {w[[n]], w[[n + 1]]};
     origo = coord@MousePosition@"CellContentsAbsolute";
     );
   onMouseDraggedCode[n_] := (
     temp = coord@MousePosition@"CellContentsAbsolute" - origo;
     w[[n]] = Min[Max[0, First@old + temp], Total@old];
     w[[n + 1]] = Total@old - w[[n]];
     );
   (* Framed is required below because it gives the expression \
margins. Otherwise, 
   if the scrollPane is set with larger than 0 FrameMargins, 
   they cannot be shrinked to zero width. *)
   grid[content_, size_] := 
    Riffle[MapThread[
      Dynamic[scrollPane[Framed[#1, FrameStyle -> None], size@#2], 
        TrackedSymbols :> {w}] &, {content, Range@Length@w}], 
     Dynamic[divPane@#, TrackedSymbols :> {w}] & /@ 
      Range@((Length@w) - 1)];

   Deploy@Grid[If[dir === "Vertical",
      List@grid[cont, {w[[#]], fix} &],
      List /@ grid[cont, {fix, w[[#]]} &]
      ], Spacings -> {0, -.1}, 
     ItemSize -> {{Table[0, {Length@w}]}, {Table[0, {Length@w}]}}],

   Initialization :> (
     (* w = width data list for all panels *)
     (* m = number of panels *)
     (* state = button states *)
     (* prev = previous state of w *)
     (* max = total width of all panels *)
     num = Length@w; state = True & /@ Range@num; 
     prev = w & /@ Range@num; max = Total@w;)
   ];
SplitPane[val_, 
    arg___] /; (Head@val === List \[And] And @@ (NumberQ /@ val)) := 
  Module[{x = val}, SplitPane[Dynamic@x, arg]];
Run Code Online (Sandbox Code Playgroud)

我们来试试一个垂直分割的窗格:

w = {200, 50, 100, 300};
SplitPane[
 Dynamic@w, {Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}],
   Null, CompleteGraph[5], "121234"}]
Run Code Online (Sandbox Code Playgroud)

垂直的例子

这是一个水平分割的窗格:

SplitPane[{50, 50, 50, 
  50}, {Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}, 
   ContentSize -> 300], Null, CompleteGraph[5], "121234"}, 
 Direction -> "Horizontal"]
Run Code Online (Sandbox Code Playgroud)

水平的例子

垂直和水平窗格组合:

xpane = {200, 300};
ypane = {200, 50};
SplitPane[Dynamic@xpane, {
  Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}],
  Dynamic[
   SplitPane[Dynamic@ypane, {CompleteGraph[5], "status"}, Last@xpane, 
    Paneled -> False, Direction -> "Horizontal"], 
   TrackedSymbols :> {xpane}]
  }, 300, Direction -> "Vertical"]
Run Code Online (Sandbox Code Playgroud)

合并的例子

我想听听您对此解决方案的想法/意见.