summaryrefslogtreecommitdiffstats
path: root/private/ole32/com/dde/client/ddeproxy.cxx
blob: bdc87f136b6c4e7787167d1a0d5484df6edbbb71 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
/*
copyright (c) 1992  Microsoft Corporation

Module Name:

    ddeproxy.cpp

Abstract:

    This module contains the code for the dde proxy (wrapper)

Author:

    Srini  Koppolu   (srinik)    22-June-1992
    Jason  Fuller   (jasonful)  24-July-1992
*/
#include "ddeproxy.h"
#include <tls.h>


DebugOnly (static UINT v_cDdeObjects=0;)
/*
 *  IMPLEMENTATION of CDdeObject
 *
 */

#ifdef OLD
#define UpdateExtent(old,new) do { if ((long)new!=old) {old=(long)new; } } while (0)
#endif

//+---------------------------------------------------------------------------
//
//  Function:   CreateDdeClientHwnd
//
//  Synopsis:   Creates a per thread ClientDde window.
//
//  Effects:    This window is created so we can keep a list of windows that
//		need to be cleaned up in the event the thread dies or OLE32 is
//		unloaded. In the case of DLL unload, we will fault if we don't
//		cleanup this window, since user will dispatch messages to
//		non-existant code. The easy way to track these windows is to
//		make them children of a common per thread window.
//
//		This routine is called by the TLSGetDdeClient() routine to
//		create a window per thread. This window doesn't need to respond
//		to DDE Initiates.
//
//  Arguments:  [void] --
//
//  Returns:    HWND to DdeClientWindow.
//
//  History:    12-10-94   kevinro   Created
//
//----------------------------------------------------------------------------

HWND CreateDdeClientHwnd(void)
{
    return SSCreateWindowExA(0,"STATIC","DdeClientHwnd",WS_DISABLED,
                         0,0,0,0,NULL,NULL,hinstSO,NULL);
}

// CreateDdeProxy
//
// This corresponds to ProxyManager::Create in 2.0
//


INTERNAL_ (LPUNKNOWN) CreateDdeProxy
    (IUnknown * pUnkOuter,
    REFCLSID clsid)
{
    LPUNKNOWN punk;
    intrDebugOut((DEB_ITRACE,"CreateDdeProxy(pUnkOuter=%x)\n",pUnkOuter));

    COleTls Tls;
    if (Tls->dwFlags & OLETLS_DISABLE_OLE1DDE)
    {
        // If DDE use is disabled we shouldn't have gotten here.
        // This is a bad place to error because we can't return an
        // HResult.
        //
        Assert(!"Executing CreateDdeProxy when DDE is disabled");
        return NULL;
    }

    punk = CDdeObject::Create (pUnkOuter, clsid);
    intrDebugOut((DEB_ITRACE,
		  "CreateDdeProxy(pUnkOuter=%x) returns %x\n",
		  pUnkOuter,
		  punk));
    return punk;
}

//+---------------------------------------------------------------------------
//
//  Method:     CDdeObject::Create
//
//  Synopsis:   Creates a CDdeObject
//
//  Effects:
//
//  Arguments:  [pUnkOuter] --  Controlling IUnknown
//      [clsid] --      OLE1 ClassID
//      [ulObjType] --  Object type. Optional: def to OT_EMBEDDED
//      [aTopic] --     Atom of link. Optional: def to NULL
//      [szItem] --     String for link object (def to NULL)
//      [ppdde] --      Output pointer to CDdeObject (def to NULL)
//      [fAllowNullClsid] -- Is NULL clsid OK? Default: false
//
//  Requires:
//
//  Returns:
//
//  Signals:
//
//  Modifies:
//
//  Derivation:
//
//  Algorithm:
//
//  History:
//
//  Notes:
//
//----------------------------------------------------------------------------
INTERNAL_(LPUNKNOWN) CDdeObject::Create
    (IUnknown *     pUnkOuter,
    REFCLSID        clsid,
    ULONG           ulObjType,// optional, default OT_EMBEDDED
    ATOM            aTopic,   // optional, only relevant if ulObjType==OT_LINK
    LPOLESTR            szItem,   // optional, only relevant if ulObjType==OT_LINK
    CDdeObject * * ppdde,       // optional, thing created
    BOOL            fAllowNullClsid) // default FALSE
{
    COleTls Tls;
    if(Tls->dwFlags & OLETLS_DISABLE_OLE1DDE)
    {
        //
        // If the DDE implementation of OLE1 is disabled
        // we shouldn't get this far.   This is also a bad place
        // to fail because we this routine is defined to not return
        // an HResult.
        //
        Assert(!"Executing CDdeObject::Create but DDE is Disabled");
        return NULL;
    }
    intrDebugOut((DEB_ITRACE,"CDdeObject::Create(%x,ulObjType=%x)\n",
          pUnkOuter,
          ulObjType));

    CDdeObject * pDdeObject;
    static int iTopic=1;  // used to make topic names unique
    WCHAR szTopic[30];
    Assert (ulObjType==OT_LINK || ulObjType==OT_EMBEDDED);

    Assert (ulObjType != OT_LINK || wIsValidAtom(aTopic));
    if (ppdde)
        *ppdde = NULL;

    if (NULL==(pDdeObject = new CDdeObject (pUnkOuter))
        || NULL == pDdeObject->m_pDataAdvHolder
        || NULL == pDdeObject->m_pOleAdvHolder)
    {
        Assert (!"new CDdeObject failed");
        return NULL;
    }

    pDdeObject->m_refs      = 1;
    pDdeObject->m_clsid     = clsid;
    pDdeObject->m_aClass    = wAtomFromCLSID(clsid);

#ifdef OLE1INTEROP

    pDdeObject->m_fOle1interop = TRUE;

#endif

    if (ulObjType==OT_LINK)
    {

        pDdeObject->m_aTopic = wDupAtom (aTopic);
        pDdeObject->m_aItem  = wGlobalAddAtom (szItem);
        // Never close a linked document
        pDdeObject->m_fNoStdCloseDoc = TRUE;
    }
    else
    {
        // This string may actually be visible in the Window Title Bar for a sec.
	InterlockedIncrement((long *)&iTopic);
        wsprintf (szTopic,OLESTR("Embedded Object #%u"), iTopic);
        Assert (lstrlenW(szTopic) < 30);
        pDdeObject->m_aItem = NULL;
        pDdeObject->m_aTopic = wGlobalAddAtom (szTopic);
    }
    pDdeObject->m_bOldSvr   = wIsOldServer (pDdeObject->m_aClass);
    pDdeObject->m_ulObjType = ulObjType;

    // we can only run if we have a MFI
    pDdeObject->m_aExeName = wGetExeNameAtom(clsid);

    intrDebugOut((DEB_ITRACE,
          "::Create(%x,aTopic=%x,aItem=%x,szItem=%ws,aExeName=%x)\n",
          pDdeObject,
          pDdeObject->m_aTopic,
          pDdeObject->m_aItem,
          szItem?szItem:L"<NULL>",
          pDdeObject->m_aExeName));

    if (ppdde)
        *ppdde = pDdeObject;
    return &pDdeObject->m_Unknown;
}



// Constructor
CDdeObject::CDdeObject (IUnknown * pUnkOuter) :
    m_Unknown(this),
    CONSTRUCT_DEBUG
    m_Data(this),
    m_Ole(this),
    m_PersistStg(this),
    m_ProxyMgr(this),
    m_OleItemContainer(this),
    m_RpcStubBuffer(this)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::CDdeObject(%x)\n",this));
    if (!pUnkOuter)
        pUnkOuter = &m_Unknown;

    m_pUnkOuter = pUnkOuter;
    m_bRunning  = FALSE;
    m_pOleClientSite = NULL;
    m_pstg = NULL;
    m_pSysChannel = NULL;
    m_pDocChannel = NULL;
    m_bInitNew = NULL;
    m_hNative = NULL;
    m_hPict   = NULL;
    m_hExtra  = NULL;
    m_cfExtra = NULL;
    m_cfPict = 0;
    m_aItem = NULL;
    m_iAdvSave = 0;
    m_iAdvClose = 0;
    m_iAdvChange = 0;
    m_fDidAdvNative = FALSE;
    m_pOleAdvHolder = NULL;
    m_pDataAdvHolder = NULL;
    m_fDidSendOnClose = FALSE;
    m_fNoStdCloseDoc = FALSE;
    m_fDidStdCloseDoc = FALSE;
    m_fDidStdOpenDoc = FALSE;
    m_fDidGetObject = FALSE;
    m_fDidLaunchApp = FALSE;
    m_fUpdateOnSave = TRUE;
    m_fVisible = FALSE;
    m_fWasEverVisible = FALSE;
    m_fCalledOnShow = FALSE;
    m_fGotCloseData = FALSE;
    m_cLocks = 1;               // connections are initially locked
    m_chk = chkDdeObj;
    m_ptd = NULL;
    m_fDoingSendOnDataChange = FALSE;
#ifdef _CHICAGO_
    //Note:POSTPPC
    _DelayDelete = NoDelay;
#endif // _CHICAGO_

    CreateOleAdviseHolder (&m_pOleAdvHolder);
    Assert (m_pOleAdvHolder);
    CreateDataAdviseHolder (&m_pDataAdvHolder);
    Assert (m_pDataAdvHolder);

#ifdef OLD
    m_cxContentExtent = 2000;  // 2 centimeters , totally random default
    m_cyContentExtent = 2000;
#endif

    m_wTerminate = Terminate_None;

    DebugOnly (v_cDdeObjects++;)
    Putsi (v_cDdeObjects);
}



CDdeObject::~CDdeObject
    (void)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::~CDdeObject(%x)\n",this));

    if (m_pDocChannel)
    {
        intrDebugOut((DEB_IWARN , "Abnormal situation: Doc Channel not deleted. Server died?"));
        delete m_pDocChannel;
    }
    if (m_pSysChannel)
    {
        Warn ("Abnormal situation: Sys Channel not deleted. Server died?");
        delete m_pSysChannel;
    }
    if (m_hNative)
    {
        GlobalFree(m_hNative);
    }

    if (m_hPict)
    {
        wFreeData (m_hPict, m_cfPict, TRUE);
    }

    if (m_hExtra)
    {
        wFreeData (m_hExtra, m_cfExtra, TRUE);
    }

    // release all the pointers that we remember

    if (m_pOleClientSite)
    {
        DeclareVisibility (FALSE);
        m_pOleClientSite->Release();
    }

    if (m_pDataAdvHolder)
        m_pDataAdvHolder->Release();

    if (m_pOleAdvHolder)
        m_pOleAdvHolder->Release();

    if (m_pstg)
        m_pstg->Release();

    if (m_aExeName)
        GlobalDeleteAtom (m_aExeName);

    if (m_aClass)
        GlobalDeleteAtom (m_aClass);

    if (m_aTopic)
        GlobalDeleteAtom (m_aTopic);

    if (m_aItem)
        GlobalDeleteAtom (m_aItem);

    if (m_ptd)
        delete m_ptd;

    m_chk = 0;
    DebugOnly (v_cDdeObjects--;)
    Putsi (v_cDdeObjects);
}




//  Handles WM_DDE_ACKs received while in initiate state. If this is the first
//  reply, save its window handle. If multiple replies are received, take the
//  one with the prefered instance, if there is one. Keep a count of
//  WM_DDE_TERMINATEs we send so that we don't shut the window until we get
//  all of the responses for  WM_DDE_TERMINATEs.


INTERNAL_(void) CDdeObject::OnInitAck (LPDDE_CHANNEL pChannel, HWND hwndSvr)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::OnInitAck(%x,hwndSvr=%x)\n",this,hwndSvr));
#ifdef _MAC
#else
    if (!IsWindow (hwndSvr))
    {
        Assert (0);
        return;
    }
    if (pChannel->hwndSvr) { // if we already have a handle
	intrDebugOut((DEB_ITRACE,
		      "CDdeObject::OnInitAck(%x,hwndSvr=%x) Already have hwndSvr=%x\n",
		      this,
		      hwndSvr,
		      pChannel->hwndSvr));
        // just take the very first one. Direct post is OK
	MPostWM_DDE_TERMINATE(hwndSvr,pChannel->hwndCli);
        // Expect an extra WM_DDE_TERMINATE
        ++pChannel->iExtraTerms;
    } else {
        // this is the server we want
        pChannel->hwndSvr = hwndSvr;
        pChannel->iExtraTerms = NULL;

	intrDebugOut((DEB_ITRACE,
		      "CDdeObject::OnInitAck(%x,hwndSvr=%x) Established Connection\n",
		      this,
		      hwndSvr,
		      pChannel->hwndSvr));
    }
#endif _MAC
}

INTERNAL_(BOOL) CDdeObject::OnAck (LPDDE_CHANNEL pChannel, LONG lParam)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::OnAck(%x,lParam=%x)\n",this,lParam));

    BOOL    retval = TRUE;
    ATOM    aItem;
    WORD    wStatus;
    HANDLE  hData;

    if( pChannel->iAwaitAck == AA_EXECUTE)
    {
       wStatus = GET_WM_DDE_EXECACK_STATUS( NULL, lParam );
       hData   = GET_WM_DDE_EXECACK_HDATA( NULL, lParam );
    }
    else
    {
       wStatus = GET_WM_DDE_ACK_STATUS( NULL, lParam );
       aItem = GET_WM_DDE_ACK_ITEM( NULL, lParam );
    }


    // check for busy bit
    if (wStatus & 0x4000)
    {
        // we got busy from the server.
        pChannel->fRejected = TRUE;
        // tell the wait loop that we got a busy ack
        //CoSetAckState(pChannel->pCI , FALSE,TRUE, SERVERCALLEX_RETRYLATER);
	intrDebugOut((DEB_ITRACE,"::OnAck(%x) Busy SetCallState(SERVERCALLEX_RETRYLATER)\n",this));
        pChannel->SetCallState(SERVERCALLEX_RETRYLATER);
        return TRUE;
    }

    // just reset the flag always
    m_wTerminate = Terminate_None;

    intrDebugOut((DEB_ITRACE,
		  "::OnAck(%x)aItem=%x(%ws) wStatus=\n",
		  this,
		  aItem,
		  wAtomName(aItem),
		  wStatus));

    if (pChannel->iAwaitAck == AA_EXECUTE)
    {
        GlobalFree (hData);
        pChannel->hCommands = NULL;
    }
    else
    {
        if (hData)
            GlobalDeleteAtom ((ATOM)hData);
    }


    // even if the client got terminate we have to go thru this path.

    if (pChannel->wTimer) {
        KillTimer (pChannel->hwndCli, 1);
        pChannel->wTimer = 0;
    }


    if (pChannel->iAwaitAck == AA_POKE)
        // We have to free the data first. OnAck can trigger
        // another Poke (like pokehostnames)
        wFreePokeData (pChannel, (m_bOldSvr && m_aClass==aMSDraw));


    if (!(wStatus & POSITIVE_ACK))
    {
	intrDebugOut((DEB_ITRACE,"::OnAck(%x) OnAck got an ack with fAck==FALSE.\n",this));

        // A negative ack is OK when doing a temporary advise from
        // IsFormatAvailable().   Also, apps don't seem to positively
        // ack all unadvises.

        // review: johannp : this is the case were have to inform the reply rejected call

        retval = FALSE;
        // we got the ack and can leave the wait loop
        //CoSetAckState(pChannel->pCI, FALSE);

	intrDebugOut((DEB_ITRACE,
		      "::OnAck(%x) ***_ NACK _*** SetCallState(ISHANDLED,RPC_E_DDE_NACK)\n",
		      this));

	pChannel->SetCallState(SERVERCALLEX_ISHANDLED, RPC_E_DDE_NACK);

        // MSDraw frees hOptions even on a NACK, despite official DDE rules.
        if (pChannel->iAwaitAck == AA_ADVISE && m_clsid != CLSID_MSDraw)
           GlobalFree (pChannel->hopt);
    }
    else
    {
        // we got the ack and can leave the wait loop
        // CoSetAckState(pChannel->pCI, FALSE);
	intrDebugOut((DEB_ITRACE,
		      "::OnAck(%x) POSITIVE_ACK SetCallState(SERVERCALLEX_ISHANDLED)\n",
		      this));
        pChannel->SetCallState(SERVERCALLEX_ISHANDLED);
    }

    pChannel->hopt = NULL;
    pChannel->iAwaitAck = NULL;
    return retval;

}





INTERNAL_(void) CDdeObject::OnTimer (LPDDE_CHANNEL pChannel)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::OnTimer(%x)\n",this));
    // Since there is only one timer for each client, just
    // repost the message and delete the timer.
#ifdef _MAC
#else
    KillTimer (pChannel->hwndCli, 1);
    pChannel->wTimer = 0;

    if (wPostMessageToServer(pChannel, pChannel->wMsg, pChannel->lParam,FALSE))
        return ;

    // Postmessage failed. We need to getback to the main stream of
    // commands for the object.
    OnAck (pChannel, pChannel->lParam);
#endif _MAC
}



// Called when we get a WM_DDE_DATA message in reponse to
// a DDE_REQUEST we sent to check if a format is available.
//
INTERNAL CDdeObject::OnDataAvailable
    (LPDDE_CHANNEL  pChannel,
    HANDLE          hDdeData,
    ATOM            aItem)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::OnDataAvailable(%x)\n",this));
    CLIPFORMAT cf;
    Assert (AA_REQUESTAVAILABLE == pChannel->iAwaitAck);
    intrAssert( wIsValidAtom(aItem));

    DDEDATA * pDdeData = (DDEDATA *) GlobalLock (hDdeData);
    RetZS (pDdeData, E_OUTOFMEMORY);
    if (!pDdeData->fAckReq && aItem)
    {
            GlobalDeleteAtom (aItem);
    }
    cf = pDdeData->cfFormat;
    GlobalUnlock (hDdeData);
    wFreeData (wHandleFromDdeData (hDdeData), cf);
    return NOERROR;
}



// Called for WM_DDE_DATA message. If data is from an ADVISE-ON-CLOSE and this
// is there are no more outstanding ADVISE-ON-CLOSE requests, close the
// document and end the conversation.


//+---------------------------------------------------------------------------
//
//  Method:     CDdeObject::OnData
//
//  Synopsis:   Called when a WM_DDE_DATA message is recieved. If the data
//		is from an ADVISE_ON_CLOSE, and there are no more
//		outstanding ADVISE_ON_CLOSE request, close the document
//		and end the conversation.
//
//  Effects:    The effects of this routine are complex.
//
//  Wow! What else can be said. This routine does alot of stuff in response
//  to an incoming WM_DDE_DATA message. There are basically two flavors of
//  response here. First is when we were expecting to get this result,
//  in which case we know what we wanted to do with the data. Second is
//  when the data just arrives, but we didn't expect it. These cases could
//  indicate that the server is shutting down.
//
//
//  Arguments:  [pChannel] -- The DDE channel recieving the message
//		[hDdeData] -- Handle to the data
//		[aItem] -- Atom to the item
//
//  Requires:
//
//  Returns:
//
//  Signals:
//
//  Modifies:
//
//  Derivation:
//
//  Algorithm:
//
//  History:    5-16-94   kevinro   Restructured and commented
//
//  Notes:
//
//
//	Be extra careful you change this routine.
//	This is especially neccesary if you are	going to exit early. The
//	way that hDdeData is free'd or kept should be understood before
//	changing.
//
//
//----------------------------------------------------------------------------
INTERNAL CDdeObject::OnData
    (LPDDE_CHANNEL  pChannel,
    HANDLE          hDdeData,
    ATOM            aItem)
{
    intrDebugOut((DEB_ITRACE,
          "CDdeObject::OnData(%x,pChannel=%x,hDdeData=%x,aItem=%x(%s)iAwaitAck=%x\n",
          this,
	  pChannel,
          hDdeData,
          aItem,
          wAtomNameA(aItem),
	  pChannel->iAwaitAck));
#ifdef _MAC
#else
    DDEDATA * lpDdeData = NULL;
    BOOL         fAck = TRUE;	
    int          iAdvOpt;
    BOOL         fCallBack;
    HRESULT      hresult = NOERROR;
    BOOL fRequested = FALSE;

    intrAssert(wIsValidAtom(aItem));

    int iAwaitAck = pChannel->iAwaitAck;

    //
    // If we were waiting for this data, then we are sitting in the
    // modal loop. Set the call state on the call control interface
    // to indicate that a response was recieved. Pass NOERROR to indicate
    // that there was success. If an error is determined later, then
    // the state will be set a second time.
    //

    if ((AA_REQUEST == iAwaitAck) || (AA_REQUESTAVAILABLE == iAwaitAck))
    {
	intrDebugOut((DEB_ITRACE,
		      "::OnData(%x) AA_REQUEST/AVAILABLE \n",
		      this));

	//
	// Regardless of the outcome of this call, we have recieved a
	// response. Set the Awaiting Ack state to nothing.
	//
        pChannel->iAwaitAck = AA_NONE;

	//
	// Determine if this channels call data is valid
	//

        if (pChannel->pCD )
	{
            //CoSetAckState(pChannel->pCI, FALSE); // clear waiting flag
	    intrDebugOut((DEB_ITRACE,"::OnData(%x) SetCallState(SERVERCALLEX_ISHANDLED)\n",this));
            pChannel->SetCallState(SERVERCALLEX_ISHANDLED);
	}
    }


    //
    // Check the string for aItem, looking for advise options. The variable
    // iAdvOpt will be set to indicate what type of data we just got, such
    // as ON_CHANGE, etc. If the option is invalid, then we won't know
    // what to do with it.
    //

    if ((hresult=wScanItemOptions (aItem, (int *) &iAdvOpt)) != NOERROR)
    {
        intrAssert(!"Item found with unknown advise option\n");
	LPARAM lp;
        if(!wPostMessageToServer (pChannel,
                          WM_DDE_ACK,
                          lp = MAKE_DDE_LPARAM (WM_DDE_ACK,NEGATIVE_ACK, aItem),TRUE))
	{
	    hresult = RPC_E_SERVER_DIED;

	}

	//
	// Did we need to free hDdeData here? No, according to the DDE spec, if the
	// receiever responds with a NACK, then the sender is responsible for
	// freeing the data.
	//
	return hresult;
    }

    //
    // If the server sent no data, there ain't much we can do about it.
    //

    if (hDdeData == NULL)
    {
	intrDebugOut((DEB_IERROR,
		      "::OnData(%x)hDdeData is NULL!\n",
		      this));

	return(RPC_E_INVALID_PARAMETER);
    }

    //
    // Lock the data into memory so we can use it. Be careful, the way
    // this routine was written originally, there are places that free
    // and realloc hDdeData. Specifically, the call to KeepData. Carefully
    // evaluate each place where you are returning, to insure the memory
    // isn't leaked. (if you have time, please restructure this routine
    // so it is easier to understand.
    //
    if (!(lpDdeData = (DDEDATA FAR *) GlobalLock(hDdeData)))
    {
	intrDebugOut((DEB_IERROR,
		      "::OnData(%x)GlobalLock on lpDdeData failed\n",
		      this));
	//
	// BUGBUG: (KevinRo)Did we need to free hDdeData here? I think
	// we should have if the fRelease flag was set. The old code
	// didn't. Need to research this further (ie you figure it out!)
	//
        return ResultFromScode (E_OUTOFMEMORY);
    }

    intrDebugOut((INTR_DDE,
    	      "::OnData(%x) lpDdeData->cfFormat=%x\n",
    	      this,
    	      (UINT)lpDdeData->cfFormat));

    //
    // The server will set fAckReq if it wants a response.
    // don't call HIC for call where not acknoewledge is requested
    //
    fAck = lpDdeData->fAckReq;

    if (pChannel->bTerminating) {
        intrDebugOut((INTR_DDE,"::OnData(%x) Got DDE_DATA in terminate sequence\n",this));
	//
	// BUGBUG: this is very dangerous since the pointer on the
	//	hDocWnd does not get deleted and a further will
	//	DDE message will GPF - we need to fix this!!!
	//
        GlobalUnlock (hDdeData);
        GlobalFree (hDdeData);
	goto exitRtn;
    }

    //
    // (KevinRo) Found this comment:
    //
    //	important that we post the acknowledge first. Otherwise the
    // 	messages are not in sync.
    //
    // The above comment might be intended to mean that the acknowledge needs to be
    // send now, because we may call one of the advise functions below, which in
    // turn may send another message to the OLE 1.0 server. Therefore, we ACK now,
    // so the messages to the OLE 1.0 server are in the correct order.
    //
    if (fAck)
    {
        LPARAM lp;
        if(!wPostMessageToServer (pChannel,
                          WM_DDE_ACK,
                          lp=MAKE_DDE_LPARAM(WM_DDE_ACK,POSITIVE_ACK, aItem),TRUE))
        {
	    return(RPC_E_SERVER_DIED);
        }
    }

    //
    // this call is now an async call and can not be rejected be HandleIncomingMessage
    //

    if ((AA_REQUESTAVAILABLE == pChannel->iAwaitAck) && (lpDdeData->fResponse))
    {
	//
	// For some reasons, OnDataAvailable will be the one to delete this data.
	// I don't understand it, but lets roll with it. (KevinRo)
	//
        GlobalUnlock (hDdeData);
        return OnDataAvailable (pChannel, hDdeData, aItem);
    }

    //
    // If the clipboard format is binary, and the topic is aStdDocName, then this
    // OnData is a RENAME
    //
    if (lpDdeData->cfFormat == (short)g_cfBinary && aItem== aStdDocName)
    {
	// ON_RENAME
	//
	// The data should be the new name, in ANSI.
	//
	ChangeTopic ((LPSTR)lpDdeData->Value);
	GlobalUnlock (hDdeData);
	GlobalFree (hDdeData);
	return(NOERROR);
    }

    //
    // Based on iAdvOpt, determine if we can callback. This one is a little
    // hard to understand. I don't either. CanCallBack appears to return
    // true if the count is 0,1, or 3, but returns FALSE if its 2 or
    // greater than 3. There are no comments in the old code as to why
    // this is. I am leaving it, since it must have been put there for
    // a reason. See CanCallBack in ddeworker.cxx for futher (ie no) details
    //
    switch (iAdvOpt)
    {
        case ON_SAVE:
            fCallBack = CanCallBack(&m_iAdvSave);
		intrDebugOut((INTR_DDE,
			      "::OnData(%x)ON_SAVE m_iAdvSave=%x\n",
			      this,
			      m_iAdvSave));

            break;
        case ON_CLOSE:
            fCallBack = CanCallBack(&m_iAdvClose);
		intrDebugOut((INTR_DDE,
			      "::OnData(%x)ON_CLOSE m_iAdvClose=%x\n",
			      this,
			      m_iAdvClose));
            break;
        case ON_CHANGE:
            fCallBack = TRUE;
		intrDebugOut((INTR_DDE,
			      "::OnData(%x)ON_CHANGE m_iAdvClose=%x\n",
			      this,
			      m_iAdvClose));
            break;
	default:
	    intrAssert( !"Unknown iAdvOpt: Somethings really broke");
    }

    // Keep the data in a cache for a future GetData call
    // which may be triggered a few lines later by the
    // SendOnDataChange().

    fRequested = lpDdeData->fResponse;


    // The call  to KeepData will change hDdeData and
    // invalidate lpDdeData. Check out KeepData for details. The net
    // result is that hDdeData is no longer valid

    GlobalUnlock (hDdeData);
    lpDdeData=NULL;

    hresult = KeepData (pChannel, hDdeData);

    //
    // This is unpleasant, but if KeepData fails, we need to
    // call SetCallState again, resetting the error code. This
    // code is such a mess that rearranging it to do
    // it in a rational way is going to be too much work given
    // the amount of time I have until shipping.
    //
    // If you have time, please simplify this code. Thanks
    //
    if (hresult != NOERROR)
    {
	//
	// At this point, hDdeData has been unlocked, and deleted by
	// the KeepData routine. Therefore, the return here doesn't
	// need to be concerned with cleaning up after hDdeData
	//
	intrDebugOut((DEB_ITRACE,
		      "::OnData(%x) KeepData failed %x\n",
		      this,
		      hresult));
        //
	// Reset the error code on the call control
	//
	if ((AA_REQUEST == iAwaitAck) || (AA_REQUESTAVAILABLE == iAwaitAck))
	{
	    if (pChannel->pCD )
	    {
		pChannel->SetCallState(SERVERCALLEX_ISHANDLED, hresult);
	    }
	}
	goto exitRtn;
    }

    if (fRequested)
    {
        // We REQUESTed the data. So, we are no longer waiting.
        // Do NOT call SendOnDataChange because the data hasn't
        // really changed again, we just requested it to satisfy
        // a call to GetData, which was probably called by the
        // real SendOnDataChange.
	intrDebugOut((INTR_DDE,
		      "::OnData(%x) fRequested DATA\n",
		      this));

        iAwaitAck = NULL;
	hresult = NOERROR;
	goto exitRtn;

    }

    //
    // Now we have decided this is data we had not asked for. This makes
    // it a change/close/saved notificiation.
    //
    intrDebugOut((INTR_DDE,"::OnData(%x) Non requested DATA\n",this));
    pChannel->AddReference();
    if (fCallBack && iAdvOpt != ON_CHANGE)
    {
	// ON_CHANGE will be handled by OleCallback, below

	intrDebugOut((INTR_DDE,
		      "::OnData(%x)Dispatching SendOnDataChange\n",
		      this));


	//
	// There are a couple of things to note about the following. First,
	// the iid of the call doesn't matter. Since OLE 1.0 servers don't
	// do nested calls, the original LID (Logical ID) can be any random
	// value. Therefore, we don't initalize it.
	//
	// According to JohannP, the calltype of these calls is supposed
	// to be CALLTYPE_SYNC. I don't fully understand why they are.
	// I am taking is decision on faith.
	//
	// Using the new call control interfaces, we do the following.
	//

	DDEDISPATCHDATA ddedispdata;
	DISPATCHDATA	dispatchdata;
	DWORD		dwFault;

	IUnknown *pUnk = m_pDataAdvHolder;

	//
	// We are about to call method #6 in the IDataAdviseHolder interface,
	// which is SendOnDataChange
	//

	RPCOLEMESSAGE	rpcMsg;
	RPC_SERVER_INTERFACE RpcInterfaceInfo;
	rpcMsg.reserved2[1] = &RpcInterfaceInfo;

	*MSG_TO_IIDPTR(&rpcMsg) = IID_IDataAdviseHolder;


	rpcMsg.Buffer = &dispatchdata;
	rpcMsg.iMethod = 6;

	dispatchdata.scode = S_OK;
	dispatchdata.pData = (LPVOID) &ddedispdata;

	ddedispdata.pCDdeObject = this;
	ddedispdata.wDispFunc = DDE_DISP_SENDONDATACHANGE;
	ddedispdata.iArg = iAdvOpt;

	// package as RPCMESSAGE and call STAInvoke
	IRpcStubBuffer * pStub = &m_RpcStubBuffer;
	hresult = STAInvoke(&rpcMsg, CALLCAT_SYNCHRONOUS, pStub, pChannel, NULL, &dwFault );
    }
    if (fCallBack )
    {
	// in 1.0 ON_CLOSE comes with data
	if (iAdvOpt==ON_CLOSE)
	{

	    intrDebugOut((INTR_DDE,
			  "::OnData(%x) iAdvOpt == ON_CLOSE, send ON_SAVE\n",
			  this));

	    m_fGotCloseData = TRUE;

	    hresult = OleCallBack(ON_SAVE,pChannel);
            if (hresult != NOERROR)
	    {
		goto errRel;
	    }

	    //ErrRtnH (DdeHandleIncomingCall(pChannel->hwndSvr, CALLTYPE_TOPLEVEL) );
	    //ErrRtnH (OleCallBack (ON_SAVE));
        }

	// check if app can handle this call
	// we do not need to call HIC for SendOnClose

	hresult = OleCallBack (iAdvOpt,pChannel);
    }

errRel:
    // Don't use pChannel after this. It can get deleted. (srinik)
    if (pChannel->ReleaseReference() == 0)
    {
	m_pDocChannel = NULL;
    }

exitRtn:
    if (!fAck && aItem)
    {
	GlobalDeleteAtom (aItem);
    }
  return hresult;
#endif _MAC
}

//+---------------------------------------------------------------------------
//
//  Method:     CDdeObject::OleCallBack
//
//  Synopsis:   Send all the right notifications whan a Save or Close happens.
//
//  Effects:    OleCallBack is a double duty function. It is called in two
//		different cases.
//
//		First, is to setup the callback, and call HandleIncomingCall.
//		Second is from DispatchCall() in the CDdeChannelControl.
//
//		The reason for doing it this way is we localize the setup
//		and processing of these calls to one routine. Therefore,
//		we can go to one spot in the code to find all of the call
//		back information.
//
//  Arguments:  [iAdvOpt] -- Which Advise operation to perform
//		[pChannel] -- Which channel is being called back
//
//  Requires:   pChannel == NULL, and the AdviseHolders are called.
//		pChannel != NULL, and the call is setup, and HandleIncomingCall
//			    is setup.
//
//  Returns:
//
//  Signals:
//
//  Modifies:
//
//  Derivation:
//
//  Algorithm:
//
//  History:    5-23-94   kevinro   Created
//
//  Notes:
//
//  WARNING: This code sucks completely. One of the major problems you need
//  to know about is that the CDdeObject may go away as part of the normal
//  processing of some of the below. Be very careful about any processing
//  that might occur after an ON_CLOSE
//
//----------------------------------------------------------------------------
INTERNAL CDdeObject::OleCallBack (int iAdvOpt, LPDDE_CHANNEL pChannel)
{
    HRESULT hresult = NOERROR;
    DDEDISPATCHDATA ddedispdata;
    DISPATCHDATA    dispatchdata;
    RPCOLEMESSAGE   rpcMsg;
    IUnknown	    *pUnk;

    RPC_SERVER_INTERFACE RpcInterfaceInfo;
    rpcMsg.reserved2[1] = &RpcInterfaceInfo;

    //
    // If the channel isn't NULL, then setup the data structures for calling
    // off to the call control.
    //
    if (pChannel != NULL)
    {
	//
	// Only do this work if we really have to
	//

	dispatchdata.scode = S_OK;
	dispatchdata.pData = (LPVOID) &ddedispdata;

	ddedispdata.pCDdeObject = this;
	ddedispdata.wDispFunc = DDE_DISP_OLECALLBACK;
	ddedispdata.iArg = iAdvOpt;
    }

    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::OleCallBack(%x,iAdvOpt=%x,pChannel=%x)\n",
		  this,
		  iAdvOpt,
		  pChannel));

    //
    // Determine what needs to be done, based on the iAdvOpt. This should be
    // one of the handled cases below, otherwise its an error.
    //
    switch (iAdvOpt)
    {
    case ON_CLOSE:
	if (pChannel != NULL)
	{
	    intrDebugOut((DEB_ITRACE,
			  "::OleCallBack(%x) setup for ON_CLOSE\n",
			  this));

	    pUnk = m_pOleAdvHolder;

	    *MSG_TO_IIDPTR(&rpcMsg) = IID_IOleAdviseHolder;
	    // IOleAdviseHolder::SendOnClose is method 8
	    rpcMsg.iMethod = 8;
	}
	else
	{
	    intrDebugOut((DEB_ITRACE,"::OleCallBack(%x) ON_CLOSE\n",this));
            DeclareVisibility (FALSE);
            RetZ (!m_fDidSendOnClose); // This SendOnClose should happen 1st
                                      // Don't let OnTerminate() do it too
            hresult = SendOnClose();

	    //
	    // WARNING WARNING WARNING: SendOnClose() may have caused the
	    // destruction of this CDdeObject. Touch nothing on the way
	    // out. Actually, if you have time, which I currently don't,
	    // see what you can do with reference counting tricks to
	    // insure this object doesn't die during this callback.
	    // Its a tricky problem, and we are shipping in 2 weeks.
	    // (KevinRo 8/6/94)
	    //
	}
        break;

    case ON_SAVE:
	if (pChannel != NULL)
	{
	    intrDebugOut((DEB_ITRACE,
			  "::OleCallBack(%x) setup for ON_SAVE\n",
			  this));

	    if (m_pOleClientSite == NULL)
	    {
		pUnk = m_pOleClientSite;
		*MSG_TO_IIDPTR(&rpcMsg) = IID_IOleClientSite;
		// IOleClientSite::SaveObject method 7
		rpcMsg.iMethod = 7;
	    }
	    else
	    {
		// Going to call the IOleAdviseHolder

		pUnk = m_pOleAdvHolder;
		*MSG_TO_IIDPTR(&rpcMsg) = IID_IOleAdviseHolder;
		// IOleAdviseHolder::SendOnSave method 7
		// (Yes, same ordinal as above, I double checked)
		rpcMsg.iMethod = 7;
	    }
	}
	else
	{

	    intrDebugOut((DEB_ITRACE,"::OleCallBack(%x) ON_SAVE\n",this));
            if (m_pOleClientSite)
            {
                // We just got data from the server, so we don't want to
                // ask him for it again when the container does a save.
                m_fUpdateOnSave = FALSE;

		// Harvard Graphics Access Violates if SaveObject is called on the ClientSite from
		// within OleCreateFromData.
		__try
		{
		    m_pOleClientSite->SaveObject();
		}
		__except (EXCEPTION_EXECUTE_HANDLER)
		{
		    intrDebugOut((DEB_IWARN ,"Warning: Exception in SaveObject\n"));
		}

                // SendOnSave is called in PS::SaveCompleted
                m_fUpdateOnSave = TRUE;
            }
            else
            {
                // Link case
                RetZS (m_pOleAdvHolder, E_OUTOFMEMORY);
                m_pOleAdvHolder->SendOnSave();
            }
	}
        break;

    case ON_CHANGE:
	if (pChannel != NULL)
	{
		// Going to call the IDataAdviseHolder

		pUnk = m_pDataAdvHolder;
		*MSG_TO_IIDPTR(&rpcMsg) = IID_IDataAdviseHolder;
		// IDataAdviseHolder::SendOnDataChange method 6
		rpcMsg.iMethod = 6;

	}
	else
	{
            RetZS (m_pDataAdvHolder, E_OUTOFMEMORY);
	    intrDebugOut((DEB_ITRACE,"::OleCallBack(%x) ON_CHANGE\n",this));
            hresult = SendOnDataChange (ON_CHANGE);
	}
	break;

    default:


	intrDebugOut((DEB_ITRACE,
		      "CDdeObject::OleCallBack(%x,iAdvOpt=%x) UNKNOWN iAdvOpt\n",
		      this,
		      iAdvOpt));
	intrAssert(!"Unexpected iAdvOpt");
	return(E_UNEXPECTED);
        break;
    }

    //
    // There are a couple of things to note about the following. First,
    // the iid of the call doesn't matter. Since OLE 1.0 servers don't
    // do nested calls, the original LID (Logical ID) can be any random
    // value. Therefore, we don't initalize it.
    //
    // According to JohannP, the calltype of these calls is supposed
    // to be CALLTYPE_SYNCHRONOUS. I don't fully understand why they are.
    // I am taking is decision on faith.
    //
    //
    // Its possible that during the handling of this call that this object
    // will get deleted. This is a pain in the butt. This means that anything
    // used after this call MUST be protected. lpCallCont happens to be one of
    // these. We have been having problems with lpCallCont being released as
    // part of the object cleanup. The call control code will access member
    // variables on its way out of the HandleDispatch. We need to bracket
    // the call below so this doesn't happen.
    //
    if (pChannel != NULL)
    {
	// dont have to worry about call control going away.
	// package as RPCMESSAGE and call STAInvoke

	DWORD		dwFault;

	rpcMsg.Buffer = &dispatchdata;

	// BUGBUG: does it matter if we package up the pUnk?
	IRpcStubBuffer * pStub = &m_RpcStubBuffer;
	hresult = STAInvoke(&rpcMsg, CALLCAT_SYNCHRONOUS, pStub, pChannel, NULL, &dwFault);
    }

    return hresult;
}


INTERNAL CDdeObject::SendOnDataChange
    (int iAdvOpt)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::SendOnDataChange(%x)\n",this));
    HRESULT hresult;
    RetZS (m_pDataAdvHolder, E_OUTOFMEMORY);
    m_fDoingSendOnDataChange = TRUE;
    hresult = m_pDataAdvHolder->SendOnDataChange (&m_Data,
						  DVASPECT_CONTENT,
						  0);
    if (ON_CLOSE==iAdvOpt)
    {
        hresult = m_pDataAdvHolder->SendOnDataChange (&m_Data,
						      DVASPECT_CONTENT,
						      ADVF_DATAONSTOP);
    }
    m_fDoingSendOnDataChange = FALSE;
    return hresult;
}




INTERNAL CDdeObject::SendOnClose
    (void)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::SendOnClose(%x)\n",this));
    RetZS (m_pOleAdvHolder, E_OUTOFMEMORY);
    m_fDidSendOnClose = TRUE;
    RetErr (m_pOleAdvHolder->SendOnClose() );
    return NOERROR;
}




INTERNAL CDdeObject::OnTerminate
    (LPDDE_CHANNEL pChannel,
    HWND hwndPost)
{
    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::OnTerminate(%x,pChannel=%x,hwndPost=%x)\n",
		  this,
		  pChannel,
		  hwndPost));

    //
    // If the hwndPost and hwndSvr are different, then it is one of two
    // cases. We could have recieved more than one Acknowlege during our
    // initiate, in which case the count iExtraTerms would have been
    // incremented, and this terminate is accounted for iExtraTerms.
    //
    // The other case is that we were terminated by a window that was
    // NOT the window we were conversing with.
    //
    if (pChannel->hwndSvr != hwndPost)
    {
	intrDebugOut((DEB_ITRACE,
		      "::OnTerminate(%x) Extra terms is 0x%x \n",
		      this,
		      pChannel->iExtraTerms));

	//
	// iExtraTerms shouldn't go below zero. If it does, something
	// has gone wrong. We have been seeing some problems with the
	// HWND mapping layer in the past. If the following condition
	// ever trips, then it is possible that another mapping
	// problem has been seen.
	//
#if DBG == 1
	if((pChannel->iExtraTerms == 0 ) &&
           (((DWORD)pChannel->hwndSvr) & (0xffff)) == ((DWORD)hwndPost & (0xffff)))
	{
	    intrDebugOut((DEB_ERROR,
			  "*** OnTerminate expected hwnd=%x got hwnd=%x ***\n",
			  pChannel->hwndSvr,hwndPost));

	    intrDebugOut((DEB_ERROR,
			  "\n*** Call KevinRo or SanfordS ***\n\n",
			  pChannel->hwndSvr,hwndPost));

	}
#endif
        --pChannel->iExtraTerms;

        intrAssert((pChannel->iExtraTerms >= 0) && "Call KevinRo or SanfordS");
        return NOERROR;
    }
    if (m_wTerminate == Terminate_Detect) {
        // we should only detect the call but not execute the code
        // set the state to Received
        m_wTerminate = Terminate_Received;
        pChannel->iAwaitAck = NULL;
        // Since Excel incorrectly did not send an ACK, we need to
        // delete the handle in the DDE message ourselves.
        if (pChannel->hCommands)
        {
            GlobalFree (pChannel->hCommands);
            pChannel->hCommands = NULL;
        }
        //CoSetAckState(pChannel->pCI, FALSE);
	intrDebugOut((DEB_ITRACE,
		      "::OnTerminate(%x) Terminate_Detect SERVERCALLEX_ISHANDLED\n",
		      this));
	pChannel->SetCallState(SERVERCALLEX_ISHANDLED, RPC_E_SERVER_DIED);
        return NOERROR;
    }

    RetZ (pChannel);
    ChkDR (this);

    if (!pChannel->bTerminating)
    {
        // Got unprompted terminate
        BOOL    bBusy;

        // Necessary safety bracket
        m_pUnkOuter->AddRef();

        bBusy = wClearWaitState (pChannel);

        if (pChannel->iAwaitAck || bBusy)
        {
            pChannel->iAwaitAck = NULL;
            //CoSetAckState(pChannel->pCI, FALSE);
	    intrDebugOut((DEB_ITRACE,"::OnTerminate(%x) !bTerminating SERVERCALLEX_ISHANDLED,RPC_E_DDE_UNEXP_MSG\n",this));
	    pChannel->SetCallState(SERVERCALLEX_ISHANDLED, RPC_E_DDE_UNEXP_MSG);
        }

        if (!m_fDidSendOnClose)
        {
	intrDebugOut((DEB_ITRACE,
		      "::OnTerminate(%x) SendOnClose from terminate\n",
		      this));

            BOOL f= m_fNoStdCloseDoc;
            m_fNoStdCloseDoc = TRUE;

            DeclareVisibility (FALSE);
            SendOnClose();

            m_fNoStdCloseDoc = f;
        }
        else
        {
	intrDebugOut((DEB_ITRACE,
		      "::OnTerminate(%x) Already did SendOnClose\n",
		      this));
            Puts ("Already did SendOnClose\n");
        }
	intrDebugOut((DEB_ITRACE,
		      "::OnTerminate(%x) Posting DDE_TERMINATE as reply\n",
		      this));

        wPostMessageToServer (pChannel, WM_DDE_TERMINATE, NULL,FALSE);

        // The terminate that we are sending itself is a reply, so we don't
        // need to do WaitForReply.
        DeleteChannel (pChannel);

        // Necessary safety bracket
        m_pUnkOuter->Release();
    }
    else
    {
	intrDebugOut((DEB_ITRACE,
		      "::OnTerminate(%x) Received DDE_TERMINATE in reply\n",
		      this));

        // We sent the WM_DDE_TERMINATE and we got the acknowledge for it
        pChannel->hwndSvr = NULL;
        pChannel->iExtraTerms = NULL;
        pChannel->iAwaitAck = NULL;
        //CoSetAckState(pChannel->pCI, FALSE);
	intrDebugOut((DEB_ITRACE,"::OnTerminate(%x) bTerminating SERVERCALLEX_ISHANDLED\n",this));
        pChannel->SetCallState(SERVERCALLEX_ISHANDLED);
    }
    Puts ("OnTerminate() done.\n");
    return NOERROR;
}




INTERNAL_(BOOL) CDdeObject::AllocDdeChannel
    (LPDDE_CHANNEL * lplpChannel, BOOL fSysWndProc)
{
    intrDebugOut((DEB_ITRACE,
	  "CDdeObject::AllocDdeChannel(%x,fSysWndClass=%x)\n",
          this,
	  fSysWndProc));

    //
    // Now try to allocate a channel
    //

    if (!(*lplpChannel =  (LPDDE_CHANNEL) new DDE_CHANNEL ))
    {
	//
	// This failed
	//
	intrAssert(*lplpChannel != NULL);
        return FALSE;
    }

    (*lplpChannel)->m_cRefs = 1;
    (*lplpChannel)->hwndSvr         = NULL;
    (*lplpChannel)->bTerminating    = FALSE;
    (*lplpChannel)->wTimer          = NULL;
    (*lplpChannel)->hDdePoke        = NULL;
    (*lplpChannel)->hCommands       = NULL;
    (*lplpChannel)->hopt            = NULL;
    (*lplpChannel)->dwStartTickCount= 0;
    (*lplpChannel)->msgFirst        = 0;
    (*lplpChannel)->msgLast         = 0;
    (*lplpChannel)->fRejected       = FALSE;
    (*lplpChannel)->wChannelDeleted = 0;
    //(*lplpChannel)->pCI             = NULL;
    (*lplpChannel)->pCD             = NULL;

    if (!((*lplpChannel)->hwndCli = DdeCreateWindowEx(0,
						      gOleWindowClass,
						      L"DDE Channel",
						      WS_CHILD,
						      0,0,0,0,
						      (HWND)TLSGetDdeClientWindow(),
						      NULL,
						      hinstSO,
						      NULL)))
    {
        intrAssert (!"Could not create AllocDdeChannel window");

	//
	// DeleteChannel will give back the CallControl
	//

        DeleteChannel(*lplpChannel);
        *lplpChannel = NULL;
        return FALSE;
    }

    // set the appropriate window procedure
    if (fSysWndProc)
    {
	SetWindowLong ((*lplpChannel)->hwndCli, GWL_WNDPROC, (LONG)SysWndProc);
    }
    else
    {
	SetWindowLong ((*lplpChannel)->hwndCli, GWL_WNDPROC, (LONG)ClientDocWndProc);
    }

    SetWindowLong ((*lplpChannel)->hwndCli, 0, (LONG) this);
    return TRUE;
}



INTERNAL_(BOOL) CDdeObject::InitSysConv()
{
    DWORD dwResult;
    intrDebugOut((DEB_ITRACE,"CDdeObject::InitSysConv(%x)\n",this));

    dwResult = wInitiate (m_pSysChannel, m_aClass, aOLE);
    if (!dwResult)
    {
       intrDebugOut((DEB_ITRACE,"\t::InitSysConv(%x) Try aSysTopic\n",this));
       dwResult = wInitiate (m_pSysChannel, m_aClass, aSysTopic);
    }

    if (!dwResult)
    {
       intrDebugOut((DEB_ITRACE,"\t::InitSysConv(%x) is failing\n",this));
    }
    return(dwResult);
}



INTERNAL_(void) CDdeObject::SetTopic(ATOM aTopic)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::SetTopic(%x)\n",this));
    intrAssert(wIsValidAtom(aTopic));
    if (m_aTopic)
        GlobalDeleteAtom (m_aTopic);

    m_aTopic = aTopic;
}



INTERNAL CDdeObject::TermConv
    (LPDDE_CHANNEL pChannel,
    BOOL fWait)     // Default==TRUE.  FALSE only in ProxyManager::Disconnect
{
    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::TermConv(%x,pChannel=%x)\n",
		  this,
		  pChannel));

    HRESULT hres;
    if (!pChannel)
    {
        return NOERROR;
    }

    pChannel->bTerminating = TRUE;

    hres = SendMsgAndWaitForReply(pChannel,
    				 AA_TERMINATE,
    				 WM_DDE_TERMINATE,
    				 0,
    				 FALSE,
    				 /*fStdCloseDoc*/FALSE,
				 /*fDetectTerminate*/ FALSE,
				 fWait);
    if (pChannel==m_pDocChannel)
    {
	DeclareVisibility (FALSE);
	if (!m_fDidSendOnClose)
	{
	    SendOnClose();
	}
    }

    DeleteChannel (pChannel);
    intrDebugOut((DEB_ITRACE,"::TermConv(%x) returns %x\n",this,hres));
    return hres;
}




INTERNAL_(void) CDdeObject::DeleteChannel (LPDDE_CHANNEL pChannel)
{
    BOOL fDocChannel = FALSE;
    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::DeleteChannel(%x,pChannel=%x)\n",
		  this,
		  pChannel));

    if (pChannel == NULL)
    {
        return;
    }

    if (pChannel == m_pDocChannel)
	fDocChannel = TRUE;



    // delete any data if we were in busy mode.
    wClearWaitState (pChannel);

    if (pChannel == m_pDocChannel)
    {
	intrDebugOut((DEB_ITRACE,
		      "::DeleteChannel(%x)Clean up pDocChannel\n",
		      this));

        // Cleanup per-conversation information
        m_fDidSendOnClose = FALSE;
        m_fDidStdCloseDoc = FALSE;
        m_ConnectionTable.Erase();
        m_iAdvSave = 0;
        m_iAdvClose= 0;
        m_fWasEverVisible = FALSE;
        m_fGotCloseData = FALSE;
        if (m_ptd)
        {
            delete m_ptd;
            m_ptd = NULL;
        }
        if (m_pstg)
        {
            m_pstg->Release();
            m_pstg = NULL;
        }
        if (m_pDataAdvHolder)
        {
            Verify (0==m_pDataAdvHolder->Release());
        }
        CreateDataAdviseHolder (&m_pDataAdvHolder);
        if (m_pOleAdvHolder)
        {
            m_pOleAdvHolder->Release(); // may not return 0 if we are
                                        // in a SendOnClose
        }
        CreateOleAdviseHolder (&m_pOleAdvHolder);
    }

    if (pChannel->hwndCli)
    {
	intrDebugOut((DEB_ITRACE,
		      "::DeleteChannel(%x)Destroy hwndCli(%x)\n",
		      this,
		      pChannel->hwndCli));

        Assert (IsWindow (pChannel->hwndCli));
        Assert (this==(CDdeObject *)GetWindowLong (pChannel->hwndCli, 0));
        Verify (SSDestroyWindow (pChannel->hwndCli));
    }

    if (pChannel == m_pDocChannel)
    {
        m_pDocChannel = NULL;
    }
    else
    {
	intrAssert(pChannel == m_pSysChannel);
        m_pSysChannel = NULL;
    }


    // Channel will be deleted in the modallp.cpp
    // if flag is on.

    if (pChannel->wChannelDeleted == Channel_InModalloop)
    {
	intrDebugOut((DEB_ITRACE,
		      "::DeleteChannel(%x) Channel(%x) in Modal Loop\n",
		      this,pChannel));

        pChannel->wChannelDeleted = Channel_DeleteNow;
    }
    else
    {
	if (pChannel->ReleaseReference() == 0)
	    pChannel = NULL;
    }

    if (fDocChannel)
	m_pDocChannel = pChannel;
}

const WCHAR  EMB_STR[]= OLESTR(" -Embedding ") ;

INTERNAL_(BOOL) CDdeObject::LaunchApp (void)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::LaunchApp(%x)\n",this));

    STARTUPINFO startInfo;
    PROCESS_INFORMATION procInfo;
    BOOL        fProcStarted;
    WCHAR       cmdline[MAX_PATH + sizeof(EMB_STR)];
    WCHAR       exeName[MAX_PATH + sizeof(cmdline)];
    //
    // Init all fields of startInfo to zero
    //
    memset((void *)&startInfo,0,sizeof(startInfo));

    //
    // The normal startup is set here.
    //
    startInfo.wShowWindow = SW_NORMAL;
    startInfo.dwFlags = STARTF_USESHOWWINDOW;

    m_fDidLaunchApp = FALSE;


    DWORD dw;

    //
    // Do our best to find the path
    //
    intrAssert(wIsValidAtom(m_aExeName));

    if (m_aExeName == 0)
    {
	//
	// There is no exe name to execute. Can't start it.
	//
	return(FALSE);
    }

    dw = SearchPath(NULL,wAtomName(m_aExeName),NULL,MAX_PATH,exeName, NULL);

    if ((dw == 0) || (dw > MAX_PATH))
    {
	intrDebugOut((DEB_ITRACE,
		      "::LaunchApp(%x) SearchPath failed. Do Default",this));
	//
	// SearchPath failed. Use the default
	//
	GlobalGetAtomName (m_aExeName, exeName, MAX_PATH);
    }

    memcpy(cmdline, EMB_STR,sizeof(EMB_STR));

    if (m_ulObjType == OT_LINK)
    {
	intrAssert(wIsValidAtom(m_aTopic));
       // File name
       Assert (wAtomName (m_aTopic));

       lstrcatW (cmdline, wAtomName (m_aTopic));
    }

    if (m_clsid == CLSID_ExcelWorksheet  // Stupid apps that show themselves
	|| m_clsid == CLSID_ExcelMacrosheet // when they're not supposed to
	|| m_clsid == CLSID_ExcelChart
	|| m_clsid == CLSID_PBrush)
    {
       startInfo.wShowWindow = SW_SHOWMINNOACTIVE;
    }

    //
    // According to the spec, the most robust way to start the app is to
    // only use a cmdline that consists of the exe name, followed by the
    // command line arguments.
    //

    lstrcatW(exeName,cmdline);

    Assert((lstrlenW(exeName)+1) < sizeof(exeName));

    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::LaunchApp(%x) Starting '%ws' \n",
		  this,
		  exeName));

    if (IsWOWThread() && IsWOWThreadCallable())
    {
        HRESULT hr;

	hr = g_pOleThunkWOW->WinExec16(exeName, startInfo.wShowWindow);

        fProcStarted = SUCCEEDED(hr);

#if DBG==1
        if (!fProcStarted)
        {
            intrDebugOut((DEB_ITRACE,
                        "::LaunchApp(%x) in Wow FAILED(%x) TO START %ws \n",
                        this,
    		        hr,
    		        exeName));
        }
#endif
    }
    else
    {
        fProcStarted = CreateProcess(NULL,
    				     exeName,
    				     NULL,
    				     NULL,
    				     FALSE,
    				     0,
    				     NULL,
    				     NULL,
    				     &startInfo,
    				     &procInfo);
        if (fProcStarted)
        {
           //
           // Let's give the server a chance to register itself. On NT,
           // CreateProcess gets the other process going, but returns
           // to let it run asynchronously. This isn't good, since we
           // need some way of knowing when it has started, so we can
           // send the DDE_INITIATES 'after' they create their DDE
           // window.
           //
           // Maximum timeout we want here shall be set at 30 seconds.
           // This should give enough time for even a 16bit WOW app to
           // start. This number was picked by trial and error. Normal
           // apps that go into an InputIdle state will return as soon
           // as they are ready. Therefore, we normally won't wait
           // the full duration.
           //

           ULONG ulTimeoutDuration = 30000L;

           //
           // Now modify this start time to handle classes
           // that have known problems. This list includes:
           //

           switch(WaitForInputIdle(procInfo.hProcess, ulTimeoutDuration))
           {
           case 0:
               intrDebugOut((DEB_ITRACE,
                      "::LaunchApp, %ws started\n",
                      exeName));
                break;
           case WAIT_TIMEOUT:
               intrDebugOut((DEB_ITRACE,
                      "::LaunchApp, %ws wait timeout at %u (dec) ms. Go Anyway\n",
                      exeName,
    		  ulTimeoutDuration));
               break;
           default:
               intrDebugOut((DEB_ITRACE,
                      "::LaunchApp, %ws unknown condition (%x)\n",
                      exeName,
                      GetLastError()));
           }
           //
           // We are already done with the Process and Thread handles
           //
           CloseHandle(procInfo.hProcess);
           CloseHandle(procInfo.hThread);
        }
        else
        {
            intrDebugOut((DEB_ITRACE,
                        "::LaunchApp(%x) FAILED(%x) TO START %ws \n",
                        this,
    		        GetLastError(),
    		        exeName));
        }
    }

    if (fProcStarted)
    {
        // If we ran the server, it should not be visible yet.
        DeclareVisibility (FALSE);
        m_fDidLaunchApp = TRUE;
    }

    return fProcStarted;
}


INTERNAL CDdeObject::MaybeUnlaunchApp (void)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::MaybeUnlaunchApp(%x)\n",this));
    if (m_fDidLaunchApp
        && !m_fDidGetObject
        && (m_clsid == CLSID_ExcelWorksheet
            || m_clsid == CLSID_ExcelMacrosheet
            || m_clsid == CLSID_ExcelChart))
    {
        return UnlaunchApp();
    }
    return NOERROR;
}




INTERNAL CDdeObject::UnlaunchApp (void)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::UnlaunchApp(%x)\n",this));
    HANDLE hCommands;
    HRESULT hresult = NOERROR;
    RetZS (AllocDdeChannel (&m_pSysChannel, TRUE), E_OUTOFMEMORY);
    ErrZS (InitSysConv(), E_UNEXPECTED);
    ErrRtnH (PostSysCommand (m_pSysChannel,(LPSTR) &achStdExit, /*bStdNew*/FALSE,
                             /*fWait*/FALSE));
    hCommands = m_pSysChannel->hCommands;
    hresult = TermConv (m_pSysChannel);

    // Since Excel incorrectly did not send an ACK, we need to
    // delete the handle ("[StdExit]") in the DDE message ourselves.
    if (hCommands)
        GlobalFree (hCommands);

    return hresult;

  errRtn:
    DeleteChannel (m_pSysChannel);
    return hresult;
}




INTERNAL CDdeObject::Execute
    (LPDDE_CHANNEL pChannel,
    HANDLE hdata,
    BOOL fStdCloseDoc,
    BOOL fWait,
    BOOL fDetectTerminate)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::Execute(%x,hdata=%x)\n",this,hdata));

    LPARAM lp=MAKE_DDE_LPARAM(WM_DDE_EXECUTE,0, hdata);

    HRESULT hr = SendMsgAndWaitForReply (pChannel,
    					 AA_EXECUTE,
                      			 WM_DDE_EXECUTE,
		      			 lp,
		      			 TRUE,
		      			 fStdCloseDoc,
		      			 fDetectTerminate,
		      			 fWait);
    if (hr == DDE_CHANNEL_DELETED)
    {
	// the channel was deleted already so dont access it!
	return S_OK;
    }

    if (SUCCEEDED(hr))
    {
	if (fStdCloseDoc)
	{
	    // Prepare to free the handle if Excel does not send an Ack
	    pChannel->hCommands = hdata;
	}
	return hr;
    }

    GlobalFree (hdata);
    return ReportResult(0, RPC_E_DDE_POST, 0, 0);
}




INTERNAL_(HRESULT) CDdeObject::AdviseOn (CLIPFORMAT cfFormat, int iAdvOn)
{
    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::AdviseOn(%x,cfFormat=%x,iAdvOn=%x)\n",
		  this,
		  cfFormat,
		  iAdvOn));

    HANDLE          hopt=NULL;
    DDEADVISE *  lpopt=NULL;
    ATOM            aItem=(ATOM)0;
    HRESULT         hresult = ReportResult(0, E_UNEXPECTED, 0, 0);

    RetZ (m_pDocChannel);

    if (NOERROR == m_ConnectionTable.Lookup (cfFormat, NULL))
    {
        // We already got a call to DataObject::Advise on this format.
	intrDebugOut((DEB_ITRACE,
		      "::AdviseOn(%x) Advise had been done on cfFormat=%x\n",
		      this,
		      cfFormat));
        return NOERROR;
    }

    UpdateAdviseCounts (cfFormat, iAdvOn, +1);

    if (m_fDidSendOnClose)
    {
	intrDebugOut((DEB_ITRACE,"::AdviseOn(%x)Ignoring Advise because we are closing\n",this));
        return NOERROR;
    }

    if (!(hopt = GlobalAlloc (GMEM_DDESHARE | GMEM_ZEROINIT, sizeof(DDEADVISE))))
    {
	intrDebugOut((DEB_ITRACE,"::AdviseOn(%x)GlobalAlloc returned NULL\n",this));
        return ReportResult(0, E_OUTOFMEMORY, 0, 0);
    }


    if (!(lpopt = (DDEADVISE FAR *) GlobalLock (hopt)))
    {
	intrDebugOut((DEB_ITRACE,"::AdviseOn(%x)GlobalLock returned NULL\n",this));
        GlobalFree (hopt);
        return ReportResult(0, E_OUTOFMEMORY, 0, 0);
    }

    lpopt->fAckReq = TRUE;
    lpopt->fDeferUpd = FALSE;
    lpopt->cfFormat = cfFormat;
    m_pDocChannel->hopt = hopt;

    if (iAdvOn == ON_RENAME)
    {
        aItem = wDupAtom (aStdDocName);
	intrAssert(wIsValidAtom(aItem));
    }
    else
    {
	intrAssert(wIsValidAtom(m_aItem));
        aItem = wExtendAtom (m_aItem, iAdvOn);
	intrAssert(wIsValidAtom(aItem));
    }

    intrDebugOut((DEB_ITRACE,
		  "::AdviseOn(%x) lpopt->cfFormat = %x, aItem=%x (%ws)\n",
		  this,
		  lpopt->cfFormat,
		  aItem,
		  wAtomName(aItem)));

    GlobalUnlock (hopt);

    LPARAM lp=MAKE_DDE_LPARAM(WM_DDE_ADVISE,hopt,aItem);
    hresult =SendMsgAndWaitForReply (m_pDocChannel,
    				     AA_ADVISE,
    				     WM_DDE_ADVISE,
                                     lp,
                                     TRUE);
    if ( FAILED(hresult) )
    {
	intrDebugOut((DEB_ITRACE,"::AdviseOn(%x)wPostMessageToServer failed\n",this));
        if (aItem)
            GlobalDeleteAtom (aItem);
        if (hopt)
            GlobalFree (hopt);
        hresult = (RPC_E_DDE_NACK == hresult) ? DV_E_CLIPFORMAT : hresult;
        intrDebugOut((DEB_ITRACE,
		      "::AdviseOn(%x) errRet, AdviseRejected, returning %x\n",
		      this,hresult));
    }

    return hresult;
}

INTERNAL CDdeObject::UpdateAdviseCounts
    (CLIPFORMAT cf,
    int         iAdvOn,
    signed int  cDelta)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::UpdateAdviseCounts(%x)\n",this));
    if (cf==g_cfBinary)
        return NOERROR;

    // Update m_iAdv* flags
    #define macro(Notif, NOTIF) \
    if (iAdvOn == ON_##NOTIF)   \
       m_iAdv##Notif += cDelta; \
    if (m_iAdv##Notif < 0)      \
        m_iAdv##Notif = 0;      \
    else if (m_iAdv##Notif > 2) \
        m_iAdv##Notif = 2;

    macro (Close, CLOSE)
    macro (Save,  SAVE)
    macro (Change,CHANGE)
    #undef macro

    Assert (m_iAdvClose < 3 && m_iAdvSave < 3 && m_iAdvChange < 3);
    Assert (m_iAdvClose >= 0 && m_iAdvSave >= 0 && m_iAdvChange >= 0);

    if (cf == g_cfNative)
    {
        if (iAdvOn != ON_CHANGE)
            m_fDidAdvNative = (cDelta > 0);
        else
	    intrDebugOut((DEB_ITRACE,
			  "::UpdateAdviseCounts(%x)Asked advise on cfNative\n",
			  this));
    }

    return NOERROR;
}




INTERNAL CDdeObject::UnAdviseOn (CLIPFORMAT cfFormat, int iAdvOn)
{
    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::UnAdviseOn(%x,cfFormat=%x,iAdvOn=%x)\n",
		  this,cfFormat,iAdvOn));
    HRESULT hr;
    ATOM aItem= (ATOM)0;

    RetZ (m_pDocChannel);
    UpdateAdviseCounts (cfFormat, iAdvOn, -1);
    if (m_fDidSendOnClose)
    {
	intrDebugOut((DEB_ITRACE,
		      "CDdeObject::UnAdviseOn(%x) Ignored because closing\n",
		      this));
        return NOERROR;
    }
    if (wTerminateIsComing (m_pDocChannel))
    {
        // We already did a StdCloseDocument, so the server is not willing
        // to do an unadvise even though the default hanlder asked us to.
	intrDebugOut((DEB_ITRACE,
		      "CDdeObject::UnAdviseOn(%x) Terminate coming\n",
		      this));
        return NOERROR;
    }

    if (iAdvOn == ON_RENAME)
    {
        aItem = wDupAtom (aStdDocName);
	intrAssert(wIsValidAtom(aItem));
    }
    else
    {
	intrAssert(wIsValidAtom(m_aItem));
        aItem = wExtendAtom (m_aItem, iAdvOn);
	intrAssert(wIsValidAtom(aItem));
    }


    // Wait For Reply
    hr = SendMsgAndWaitForReply (m_pDocChannel,
    				 AA_UNADVISE,
    				 WM_DDE_UNADVISE,
                                 MAKE_DDE_LPARAM (WM_DDE_UNADVISE,cfFormat,aItem),
                                 FALSE,
                                 FALSE);
    if (hr != NOERROR && hr != RPC_E_DDE_NACK)
    {
        if (aItem)
            GlobalDeleteAtom (aItem);
	intrDebugOut((DEB_ITRACE,
		      "::UnAdviseOn(%x)WaitForReply returns %x\n",
		      this));
        return hr;
    }


    if (cfFormat==m_cfPict)
    {
        if (m_hPict)
        {
            // Invalidate the cache so when someone explicitly asks for
            // the data, they will get fresh data.
            wFreeData (m_hPict, m_cfPict, TRUE);
            m_hPict = (HANDLE)0;
            m_cfPict = 0;
        }
    }

    // Due to a bug in the OLE1 libraries, unadvising on a presentation
    // format effectively unadvises on native.
    if (cfFormat != g_cfNative && m_fDidAdvNative)
    {
        if (iAdvOn == ON_SAVE)
        {
            // to reflect the fact that the native advise connection was lost
            m_iAdvSave--;
            m_fDidAdvNative = FALSE;
            RetErr (AdviseOn (g_cfNative, ON_SAVE));  // re-establish
        }
        else if (iAdvOn == ON_CLOSE)
        {
            // to reflect the fact that the native advise connection was lost
            m_iAdvClose--;
            m_fDidAdvNative = FALSE;
            RetErr (AdviseOn (g_cfNative, ON_CLOSE));
        }
    }

    return NOERROR;
}


//
// Post a message to a 1.0 server (callee) and wait for the acknowledge
//


INTERNAL CDdeObject::Poke
    (ATOM aItem, HANDLE hDdePoke)
{
    HRESULT hr;

    intrDebugOut((DEB_ITRACE,"CDdeObject::Poke(%x)\n",this));

    ATOM aTmpItem;

    intrAssert(wIsValidAtom(aItem));

    aTmpItem = wDupAtom (aItem);

    intrAssert(wIsValidAtom(aTmpItem));

    m_pDocChannel->hDdePoke = hDdePoke;

    LPARAM lp = MAKE_DDE_LPARAM(WM_DDE_POKE,hDdePoke,aTmpItem);
    hr = SendMsgAndWaitForReply (m_pDocChannel,
                                 AA_POKE,
                                 WM_DDE_POKE,
                                 lp,
                                 TRUE);
    if (S_OK == hr)
    {
	intrDebugOut((DEB_ITRACE,"::Poke(%x) returning %x\n",this,hr));
        return hr;
    }

    intrDebugOut((DEB_ITRACE,"::Poke(%x)wPostMessage failed %x\n",this,hr));
    // Error case
    if (aTmpItem)
        GlobalDeleteAtom (aTmpItem);
    wFreePokeData (m_pDocChannel, m_bOldSvr && m_aClass==aMSDraw);
    hr = RPC_E_DDE_POST;
    intrDebugOut((DEB_ITRACE,"::Poke(%x)wPostMessage returns %x\n",this,hr));
    return hr;

}

INTERNAL CDdeObject::PostSysCommand
    (LPDDE_CHANNEL pChannel,
    LPCSTR szCmd,
    BOOL fStdNew,
    BOOL fWait)
{
    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::PostSysCommand(%x,szCmd=%s,fStdNew=%x,fWait=%x)\n",
		  this,
		  szCmd,
		  fStdNew,
		  fWait));

    ULONG    size;
    WORD   len;
    LPSTR  lpdata= NULL;
    HANDLE hdata = NULL;
    HRESULT hresult;


    #define LN_FUDGE        16     // [],(), 3 * 3 (2 double quotes and comma)

    len =  strlen (szCmd);

    // for StdNewDocument command add class name
    if (fStdNew)
        len += wAtomLenA (m_aClass);

    // Now add the document length.
    len += wAtomLenA (m_aTopic);

    // now add the fudge factor for the Quotes etc.
    len += LN_FUDGE;

    // allocate the buffer and set the command.
    if (!(hdata = GlobalAlloc (GMEM_DDESHARE, size = len)))
        return ReportResult(0, E_OUTOFMEMORY, 0, 0);

    if (!(lpdata = (LPSTR)GlobalLock (hdata))) {
        Assert (0);
        GlobalFree (hdata);
        return ReportResult(0, E_OUTOFMEMORY, 0, 0);
    }

    strcpy (lpdata, (LPSTR)"["); // [
    strcat (lpdata, szCmd);      // [StdCmd
    if (strcmp (szCmd, "StdExit"))
    {
        strcat (lpdata, "(\"");      // [StdCmd("

        if (fStdNew)
        {
            len = strlen (lpdata);
            GlobalGetAtomNameA (m_aClass, (LPSTR)lpdata + len, size-len);
                                                // [StdCmd("class
            strcat (lpdata, "\",\"");          // [StdCmd("class","
        }

        len = strlen (lpdata);
        // now get the topic name.
        GlobalGetAtomNameA (m_aTopic, lpdata + len, (WORD)size - len);
                                                // [StdCmd("class","topic
        strcat (lpdata, "\")");                // [StdCmd("class","topic")
    }
    strcat (lpdata, "]");
    Assert (strlen(lpdata) < size);
    intrDebugOut((DEB_ITRACE,"::PostSysCommand(%x) hData(%s)\n",this,lpdata));
    GlobalUnlock (hdata);

    // return Execute (m_pSysChannel, hdata, /*fStdClose*/FALSE, fWait);
    // REVIEW: this fixed bug 1856 (johannp)
    // JasonFul - does it break something else?

    hresult = Execute (m_pSysChannel,
		       hdata,
		       /*fStdClose*/FALSE,
		       fWait,
		       /*fDetectTerminate*/ TRUE);

    intrDebugOut((DEB_ITRACE,"::PostSysCommand(%x) returns:%x\n",this,hresult));
    return hresult;

}

//+---------------------------------------------------------------------------
//
//  Method:     CDdeObject::KeepData
//
//  Synopsis: Given the DDEDATA structure from a WM_DDE_DATA message, extract
// 		the real data and keep it till GetData or Save is done.
//
//
//  Effects:
//
//  Arguments:  [pChannel] --
//		[hDdeData] --
//
//  Requires:
//
//  Returns:	E_OUTOFMEMORY or E_HANDLE if failure, NOERROR if success
//		
//
//  Signals:
//
//  Modifies:
//
//  Derivation:
//
//  Algorithm:
//
//  History:    5-14-94   kevinro   Commented
//
//  Notes:
//
//----------------------------------------------------------------------------
INTERNAL CDdeObject::KeepData
    (LPDDE_CHANNEL pChannel, HANDLE hDdeData)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::KeepData(%x)\n",this));

    DDEDATA *   lpDdeData = NULL;
    HANDLE          hData;
    CLIPFORMAT      cfFormat;



    if (!(lpDdeData = (DDEDATA *) (GlobalLock (hDdeData))))
    {
        return E_OUTOFMEMORY;;
    }


    cfFormat = lpDdeData->cfFormat;
    intrDebugOut((DEB_ITRACE,
		  "::KeepData(%x) Keeping cfFormat=%x\n",
		  this,
		  cfFormat));

    GlobalUnlock (hDdeData);

    // Possible Side effect of wHandleFromDdeData() is the freeing of hDdeData
    if (!(hData = wHandleFromDdeData (hDdeData))
        || !wIsValidHandle (hData, cfFormat) )
    {
        Assert(0);
        return ReportResult(0, E_OUTOFMEMORY, 0, 0);
    }

    if (cfFormat == g_cfNative) {
        if (m_hNative)
            GlobalFree (m_hNative);
        // Keep the native data
        RetErr (wTransferHandle (&m_hNative, &hData, cfFormat));
    }
    else if (cfFormat == CF_METAFILEPICT ||
             cfFormat == CF_BITMAP       ||
             cfFormat == CF_DIB)
    {
        if (m_hPict)
            wFreeData (m_hPict, m_cfPict, TRUE);
        m_cfPict = cfFormat;
        // Keep the presentation data
        RetErr (wTransferHandle (&m_hPict, &hData, cfFormat));

#ifdef OLD
        // Remember size of picture so we can return
        // a reasonable answer for GetExtent
        if (cfFormat == CF_METAFILEPICT)
        {
            LPMETAFILEPICT  lpMfp = (LPMETAFILEPICT) GlobalLock (m_hPict);
            if (NULL==lpMfp)
                return E_HANDLE;
            UpdateExtent (m_cxContentExtent, lpMfp->xExt);
            UpdateExtent (m_cyContentExtent, lpMfp->yExt);
            GlobalUnlock (m_hPict);
        }
        else if (cfFormat==CF_BITMAP)
        {
            BITMAP bm;
            if (0==GetObject (m_hPict, sizeof(BITMAP), (LPVOID) &bm))
                return E_HANDLE;
            UpdateExtent (m_cxContentExtent,
                            wPixelsToHiMetric (bm.bmWidth, giPpliX));
            UpdateExtent (m_cyContentExtent,
                            wPixelsToHiMetric (bm.bmHeight,giPpliY));
        }
        else if (cfFormat==CF_DIB)
        {
            BITMAPINFOHEADER * pbminfohdr;
            pbminfohdr = (BITMAPINFOHEADER *) GlobalLock (m_hPict);
            if (NULL==pbminfohdr)
                return E_HANDLE;
            UpdateExtent (m_cxContentExtent,
                            wPixelsToHiMetric (pbminfohdr->biWidth, giPpliX));
            UpdateExtent (m_cyContentExtent,
                             wPixelsToHiMetric (pbminfohdr->biHeight,giPpliY));
            GlobalUnlock (m_hPict);
        }
#endif

    }
    else
    {
        if (m_hExtra)
            wFreeData (m_hExtra, m_cfExtra, TRUE);
        m_cfExtra = cfFormat;
        wTransferHandle (&m_hExtra, &hData, cfFormat);
    }

    return NOERROR;
}


// IsFormatAvailable
//
// Does a temporary DDE_REQUEST to see if server supports a format
// Returns NOERROR if format is available.
//


INTERNAL CDdeObject::IsFormatAvailable
    (LPFORMATETC pformatetc)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::IsFormatAvailable(%x)\n",this));
    ATOM    aItem=(ATOM)0;
    HRESULT hresult;
    LPARAM lp = 0;

    Puts ("DdeObject::IsFormatAvailable\n");

    if (!HasValidLINDEX(pformatetc))
    {
        intrDebugOut((DEB_IERROR, "\t!HasValidLINDEX(pformatetc)\n"));
        return(DV_E_LINDEX);
    }

    if (0==pformatetc->cfFormat)
        return ResultFromScode (E_INVALIDARG);

    if (pformatetc->dwAspect & DVASPECT_ICON)
    {
        if (pformatetc->cfFormat==CF_METAFILEPICT)
        {
            // This is always available. we get it from the exe.
            return NOERROR;
        }
        // an icon must be a metafile
        return ResultFromScode (S_FALSE);
    }
    if (!(pformatetc->dwAspect & (DVASPECT_CONTENT | DVASPECT_DOCPRINT)))
    {
        // 1.0 does not support Thumb.
        return ReportResult(0, S_FALSE, 0, 0);
    }

    if (NOERROR == (hresult=m_ConnectionTable.Lookup (pformatetc->cfFormat, NULL)))
    {
        // We already got a call to DataObject::Advise on this format,
        // so it must be available.
        Puts ("DataObject::Advise had been done on this format.\n");
        return NOERROR;
    }
    else
    {
        // Lookup () didn't find this format.
        ErrZ (GetScode(hresult)==S_FALSE);
    }

    intrAssert(wIsValidAtom(m_aItem));
    aItem = wDupAtom (m_aItem);
    intrAssert(wIsValidAtom(aItem));

    lp = MAKE_DDE_LPARAM (WM_DDE_REQUEST,pformatetc->cfFormat,aItem);
    if(NOERROR==SendMsgAndWaitForReply (m_pDocChannel,
    				        AA_REQUESTAVAILABLE,
    				        WM_DDE_REQUEST,
                              	        lp,
                              	        TRUE))
        return NOERROR;

    // Last ditch effort: Advise
    if (NOERROR== AdviseOn (pformatetc->cfFormat, ON_SAVE))
    {
        // We cannot Unadvise because an OLE 1.0 bug
        // terminates DDE advise connections for ALL formats.
        //// UnAdviseOn (pformatetc->cfFormat, ON_SAVE);
        // Instead, just remember we did this advise.
        m_ConnectionTable.Add (0, pformatetc->cfFormat, ADVFDDE_ONSAVE);
        return NOERROR;
    }
    return ResultFromScode (S_FALSE);

errRtn:
    AssertSz (0, "Error in CDdeObject::IsFormatAvailable");
    Puth (hresult); Putn();
    if (aItem)
        GlobalDeleteAtom (aItem);

    return hresult;
}




INTERNAL CDdeObject::ChangeTopic
    (LPSTR lpszTopic)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::ChangeTopic(%x,lpszTopic=%s)\n",this,lpszTopic));
    HRESULT hresult;
    LPMONIKER pmkFile=NULL;
    LPMONIKER pmkItem=NULL;
    LPMONIKER pmkComp=NULL;
    LPMONIKER pmkNewName=NULL;
    ATOM aTopic = wGlobalAddAtomA (lpszTopic);
    intrAssert(wIsValidAtom(aTopic));

    // Yet-Another-Excel-Hack
    // Excel 4.0 sends StdDocumentName every time it saves,
    // whether or not the file name has actually changed. Bug 2957
    if (aTopic != m_aTopic)
    {
        ErrRtnH (CreateOle1FileMoniker (wAtomName(aTopic), m_clsid, &pmkFile));
        if (m_aItem)
        {
            intrAssert (wIsValidAtom (m_aItem));
            ErrRtnH (CreateItemMoniker (OLESTR("!"), wAtomName (m_aItem), &pmkItem));
            ErrRtnH (CreateGenericComposite (pmkFile, pmkItem, &pmkComp));
            (pmkNewName = pmkComp)->AddRef();
        }
        else
        {
            (pmkNewName = pmkFile)->AddRef();
        }
        RetZS (m_pOleAdvHolder, E_OUTOFMEMORY);
        RetZ (pmkNewName);
        ErrRtnH (m_pOleAdvHolder->SendOnRename (pmkNewName));
    }
    SetTopic (aTopic);
    hresult = NOERROR;

  errRtn:
    if (pmkFile)
        pmkFile->Release();
    if (pmkItem)
        pmkItem->Release();
    if (pmkComp)
        pmkComp->Release();
    if (pmkNewName)
        pmkNewName->Release();
    return hresult;
}


//+---------------------------------------------------------------------------
//
//  Method:     CDdeObject::ChangeItem
//
//  Synopsis:   Changes the m_aItem atom, using an Ansi string
//
//  Effects:
//
//  Arguments:  [szItem] -- Ansi string for the new item
//
//  Requires:
//
//  Returns:
//
//  Signals:
//
//  Modifies:
//
//  Derivation:
//
//  Algorithm:
//
//  History:    5-12-94   kevinro   Created
//
//  Notes:
//
//----------------------------------------------------------------------------
INTERNAL_(void) CDdeObject::ChangeItem
    (LPSTR szItem)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::ChangeItem(%x,szItem=%s)\n",this,szItem));
    intrAssert(wIsValidAtom(m_aItem));
    if (m_aItem)
        GlobalDeleteAtom (m_aItem);
    m_aItem = wGlobalAddAtomA (szItem);
    intrAssert(wIsValidAtom(m_aItem));
}




INTERNAL CDdeObject::DeclareVisibility
    (BOOL f,
    BOOL fCallOnShowIfNec)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::DelcareVisibility(%x)\n",this));
    if (f)
        m_fWasEverVisible = TRUE;
    if ((f && (!m_fVisible || !m_fCalledOnShow)) ||
        (!f && m_fVisible))
    {
        if (m_pOleClientSite && fCallOnShowIfNec && m_clsid != CLSID_Package)
        {
            m_pOleClientSite->OnShowWindow (f);
            m_fCalledOnShow = f;
        }
        m_fVisible = f;
    }
    return NOERROR;
}



INTERNAL CDdeObject::Update
    (BOOL fRequirePresentation)
{
    intrDebugOut((DEB_ITRACE,
		  "CDdeObject::Update(%x,fRequiredPresentation=%x)\n",
		  this,
		  fRequirePresentation));
    // Get latest data
    // OLE 1.0 spec says servers must supply metafile format.
    HRESULT hresult = RequestData (m_cfPict ? m_cfPict : CF_METAFILEPICT);
    if (fRequirePresentation && hresult!=NOERROR)
        return hresult;
    RetErr (RequestData (g_cfNative));
    SendOnDataChange (ON_CHANGE);
    return NOERROR;
}



INTERNAL CDdeObject::Save
    (LPSTORAGE pstg)
{
    intrDebugOut((DEB_ITRACE,"CDdeObject::Save(%x)\n",this));
    VDATEIFACE (pstg);
#ifdef OLE1INTEROP
    RetErr (StSave10NativeData (pstg, m_hNative, m_fOle1interop));
#else
    RetErr (StSave10NativeData (pstg, m_hNative, FALSE));
#endif
    if (m_aItem)
    {
	intrAssert(wIsValidAtom(m_aItem));
        RetErr (StSave10ItemName (pstg, wAtomNameA (m_aItem)));
    }
    RetErr (wWriteFmtUserType (pstg, m_clsid));
    return NOERROR;
}

/*
 *  IMPLEMENTATION of CUnknownImpl
 *
 */



STDMETHODIMP_(ULONG) NC(CDdeObject,CUnknownImpl)::AddRef()
{
    ChkD(m_pDdeObject);

    return InterlockedAddRef(&(m_pDdeObject->m_refs));
}


STDMETHODIMP_(ULONG) NC(CDdeObject,CUnknownImpl)::Release()
{
    ChkD(m_pDdeObject);
    Assert (m_pDdeObject->m_refs != 0);
    ULONG ul;

    if ((ul=InterlockedRelease(&(m_pDdeObject->m_refs))) == 0) {
        m_pDdeObject->m_ProxyMgr.Disconnect();

#ifdef _CHICAGO_
	//Note:POSTPPC
	// the object can not be delete if guarded
	// which is the case if DelayDelete state is 'DelayIt'
	//
	if (m_pDdeObject->_DelayDelete == DelayIt)
	{
	    // set the state to ReadyToDelete and
	    // the object will be deleted at the
	    // UnGuard call
	    m_pDdeObject->_DelayDelete = ReadyToDelete;
	    intrDebugOut((DEB_IWARN ,"Can not release CDdeObject\n"));
	    return 1;
	}
#endif //_CHICAGO_
	delete m_pDdeObject;
        return 0;
    }
    return ul;
}




STDMETHODIMP NC(CDdeObject,CUnknownImpl)::QueryInterface(REFIID iid, LPLPVOID ppv)
{
    ChkD(m_pDdeObject);
    if (iid == IID_IUnknown) {
        *ppv = (void FAR *)&m_pDdeObject->m_Unknown;
        AddRef();
        return NOERROR;
    }
    else if (iid ==  IID_IOleObject)
        *ppv = (void FAR *) &(m_pDdeObject->m_Ole);
    else if (iid ==  IID_IDataObject)
        *ppv = (void FAR *) &(m_pDdeObject->m_Data);
    else if (iid ==  IID_IPersist || iid == IID_IPersistStorage)
        *ppv = (void FAR *) &(m_pDdeObject->m_PersistStg);
    else if (iid == IID_IProxyManager)
        *ppv = (void FAR *) &(m_pDdeObject->m_ProxyMgr);
    else if (iid == IID_IOleItemContainer
             || iid == IID_IOleContainer
             || iid == IID_IParseDisplayName)
        *ppv = (void FAR *) &(m_pDdeObject->m_OleItemContainer);
    else {
        Puts ("INTERFACE NOT FOUND \r\n");
        *ppv = NULL;
        return ReportResult(0, E_NOINTERFACE, 0, 0);
    }

    m_pDdeObject->m_pUnkOuter->AddRef();
    return NOERROR;
}


// implementations of IRpcStubBuffer methods
STDUNKIMPL_FORDERIVED(DdeObject, RpcStubBufferImpl)



STDMETHODIMP NC(CDdeObject,CRpcStubBufferImpl)::Connect
    (IUnknown * pUnkServer )
{
    // do nothing
    return S_OK;
}

STDMETHODIMP_(void) NC(CDdeObject,CRpcStubBufferImpl)::Disconnect
    ()
{
    // do nothing
}

STDMETHODIMP_(IRpcStubBuffer*) NC(CDdeObject,CRpcStubBufferImpl)::IsIIDSupported
    (REFIID riid)
{
    // do nothing
    return NULL;
}


STDMETHODIMP_(ULONG) NC(CDdeObject,CRpcStubBufferImpl)::CountRefs
    ()
{
    // do nothing
    return 1;
}

STDMETHODIMP NC(CDdeObject,CRpcStubBufferImpl)::DebugServerQueryInterface
    (void ** ppv )
{
    // do nothing
    *ppv = NULL;
    return S_OK;
}


STDMETHODIMP_(void) NC(CDdeObject,CRpcStubBufferImpl)::DebugServerRelease
    (void * pv)
{
    // do nothing
}

STDMETHODIMP NC(CDdeObject,CRpcStubBufferImpl)::Invoke
    (RPCOLEMESSAGE *_prpcmsg, IRpcChannelBuffer *_pRpcChannelBuffer)
{
    PDISPATCHDATA pdispdata = (PDISPATCHDATA) _prpcmsg->Buffer;
    return DispatchCall( pdispdata );
}


// implementation of IRpcChannelBuffer methods for DDE_CHANNEL
//

STDMETHODIMP DDE_CHANNEL::QueryInterface ( REFIID riid, LPVOID * ppvObj)
{
    *ppvObj = this;
    return S_OK;
}
STDMETHODIMP_(ULONG) DDE_CHANNEL::AddRef ()
{
    return 1;
}
STDMETHODIMP_(ULONG) DDE_CHANNEL::Release ()
{
    return 1;
}

// Provided IRpcChannelBuffer methods (for callback methods side)
HRESULT  DDE_CHANNEL::GetBuffer(
/* [in] */ RPCOLEMESSAGE __RPC_FAR *pMessage,
/* [in] */ REFIID riid)
{
    return S_OK;
}

HRESULT  DDE_CHANNEL::SendReceive(
/* [out][in] */ RPCOLEMESSAGE __RPC_FAR *pMessage,
/* [out] */ ULONG __RPC_FAR *pStatus)
{
    return S_OK;
}

HRESULT  DDE_CHANNEL::FreeBuffer(
/* [in] */ RPCOLEMESSAGE __RPC_FAR *pMessage)
{
    return S_OK;
}

HRESULT  DDE_CHANNEL::GetDestCtx(
/* [out] */ DWORD __RPC_FAR *pdwDestContext,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppvDestContext)
{
    *pdwDestContext = MSHCTX_LOCAL;
    return S_OK;
}

HRESULT  DDE_CHANNEL::IsConnected( void)
{
    return S_OK;
}