FlatCAMApp.py 472 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import winreg
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool
  28. import socket
  29. from array import array
  30. # #######################################
  31. # # Imports part of FlatCAM ##
  32. # #######################################
  33. from ObjectCollection import *
  34. from FlatCAMObj import *
  35. from flatcamGUI.PlotCanvas import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. fcTranslate.apply_language('strings')
  53. if '_' not in builtins.__dict__:
  54. _ = gettext.gettext
  55. # ########################################
  56. # # App ###
  57. # ########################################
  58. class App(QtCore.QObject):
  59. """
  60. The main application class. The constructor starts the GUI.
  61. """
  62. # Get Cmd Line Options
  63. cmd_line_shellfile = ''
  64. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  65. try:
  66. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  67. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  68. except getopt.GetoptError:
  69. print(cmd_line_help)
  70. sys.exit(2)
  71. for opt, arg in cmd_line_options:
  72. if opt == '-h':
  73. print(cmd_line_help)
  74. sys.exit()
  75. elif opt == '--shellfile':
  76. cmd_line_shellfile = arg
  77. # ## Logging ###
  78. log = logging.getLogger('base')
  79. log.setLevel(logging.DEBUG)
  80. # log.setLevel(logging.WARNING)
  81. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  82. handler = logging.StreamHandler()
  83. handler.setFormatter(formatter)
  84. log.addHandler(handler)
  85. # ##########################################################################
  86. # ################## Version and VERSION DATE ##############################
  87. # ##########################################################################
  88. version = 8.97
  89. version_date = "2019/09/15"
  90. beta = True
  91. # current date now
  92. date = str(datetime.today()).rpartition('.')[0]
  93. date = ''.join(c for c in date if c not in ':-')
  94. date = date.replace(' ', '_')
  95. # URL for update checks and statistics
  96. version_url = "http://flatcam.org/version"
  97. # App URL
  98. app_url = "http://flatcam.org"
  99. # Manual URL
  100. manual_url = "http://flatcam.org/manual/index.html"
  101. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  102. # this variable will hold the project status
  103. # if True it will mean that the project was modified and not saved
  104. should_we_save = False
  105. # flag is True if saving action has been triggered
  106. save_in_progress = False
  107. # ###########################################################################
  108. # ############################# Signals ################################
  109. # ###########################################################################
  110. # Inform the user
  111. # Handled by:
  112. # * App.info() --> Print on the status bar
  113. inform = QtCore.pyqtSignal(str)
  114. app_quit = QtCore.pyqtSignal()
  115. # General purpose background task
  116. worker_task = QtCore.pyqtSignal(dict)
  117. # File opened
  118. # Handled by:
  119. # * register_folder()
  120. # * register_recent()
  121. # Note: Setting the parameters to unicode does not seem
  122. # to have an effect. Then are received as Qstring
  123. # anyway.
  124. # File type and filename
  125. file_opened = QtCore.pyqtSignal(str, str)
  126. # File type and filename
  127. file_saved = QtCore.pyqtSignal(str, str)
  128. # Percentage of progress
  129. progress = QtCore.pyqtSignal(int)
  130. plots_updated = QtCore.pyqtSignal()
  131. # Emitted by new_object() and passes the new object as argument, plot flag.
  132. # on_object_created() adds the object to the collection, plots on appropriate flag
  133. # and emits new_object_available.
  134. object_created = QtCore.pyqtSignal(object, bool, bool)
  135. # Emitted when a object has been changed (like scaled, mirrored)
  136. object_changed = QtCore.pyqtSignal(object)
  137. # Emitted after object has been plotted.
  138. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  139. object_plotted = QtCore.pyqtSignal(object)
  140. # Emitted when a new object has been added or deleted from/to the collection
  141. object_status_changed = QtCore.pyqtSignal(object, str)
  142. message = QtCore.pyqtSignal(str, str, str)
  143. # Emmited when shell command is finished(one command only)
  144. shell_command_finished = QtCore.pyqtSignal(object)
  145. # Emitted when multiprocess pool has been recreated
  146. pool_recreated = QtCore.pyqtSignal(object)
  147. # Emitted when an unhandled exception happens
  148. # in the worker task.
  149. thread_exception = QtCore.pyqtSignal(object)
  150. # used to signal that there are arguments for the app
  151. args_at_startup = QtCore.pyqtSignal(list)
  152. # a reusable signal to replot a list of objects
  153. # should be disconnected after use so it can be reused
  154. replot_signal = pyqtSignal(list)
  155. def __init__(self, user_defaults=True, post_gui=None):
  156. """
  157. Starts the application.
  158. :return: app
  159. :rtype: App
  160. """
  161. App.log.info("FlatCAM Starting...")
  162. self.main_thread = QtWidgets.QApplication.instance().thread()
  163. # ############################################################################
  164. # # ################# OS-specific ############################################
  165. # ############################################################################
  166. portable = False
  167. # Folder for user settings.
  168. if sys.platform == 'win32':
  169. # #########################################################################
  170. # Setup the listening thread for another instance launching with args #####
  171. # #########################################################################
  172. # make sure the thread is stored by using a self. otherwise it's garbage collected
  173. self.th = QtCore.QThread()
  174. self.th.start(priority=QtCore.QThread.LowestPriority)
  175. self.new_launch = ArgsThread()
  176. self.new_launch.open_signal[list].connect(self.on_startup_args)
  177. self.new_launch.moveToThread(self.th)
  178. self.new_launch.start.emit()
  179. from win32com.shell import shell, shellcon
  180. if platform.architecture()[0] == '32bit':
  181. App.log.debug("Win32!")
  182. else:
  183. App.log.debug("Win64!")
  184. # #########################################################################
  185. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  186. # #########################################################################
  187. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  188. try:
  189. with open(config_file, 'r') as f:
  190. try:
  191. for line in f:
  192. param = str(line).rpartition('=')
  193. if param[0] == 'portable':
  194. try:
  195. portable = eval(param[2])
  196. except NameError:
  197. portable = False
  198. except Exception as e:
  199. log.debug('App.__init__() -->%s' % str(e))
  200. return
  201. except FileNotFoundError:
  202. pass
  203. if portable is False:
  204. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  205. else:
  206. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  207. self.os = 'windows'
  208. else: # Linux/Unix/MacOS
  209. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  210. self.os = 'unix'
  211. # ##########################################################################
  212. # ################## Setup folders and files ###############################
  213. # ##########################################################################
  214. if not os.path.exists(self.data_path):
  215. os.makedirs(self.data_path)
  216. App.log.debug('Created data folder: ' + self.data_path)
  217. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  218. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  219. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  220. if not os.path.exists(self.postprocessorpaths):
  221. os.makedirs(self.postprocessorpaths)
  222. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  223. # create current_defaults.FlatConfig file if there is none
  224. try:
  225. f = open(self.data_path + '/current_defaults.FlatConfig')
  226. f.close()
  227. except IOError:
  228. App.log.debug('Creating empty current_defaults.FlatConfig')
  229. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  230. json.dump({}, f)
  231. f.close()
  232. # create factory_defaults.FlatConfig file if there is none
  233. try:
  234. f = open(self.data_path + '/factory_defaults.FlatConfig')
  235. f.close()
  236. except IOError:
  237. App.log.debug('Creating empty factory_defaults.FlatConfig')
  238. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  239. json.dump({}, f)
  240. f.close()
  241. try:
  242. f = open(self.data_path + '/recent.json')
  243. f.close()
  244. except IOError:
  245. App.log.debug('Creating empty recent.json')
  246. f = open(self.data_path + '/recent.json', 'w')
  247. json.dump([], f)
  248. f.close()
  249. try:
  250. fp = open(self.data_path + '/recent_projects.json')
  251. fp.close()
  252. except IOError:
  253. App.log.debug('Creating empty recent_projects.json')
  254. fp = open(self.data_path + '/recent_projects.json', 'w')
  255. json.dump([], fp)
  256. fp.close()
  257. # Application directory. CHDIR to it. Otherwise, trying to load
  258. # GUI icons will fail as their path is relative.
  259. # This will fail under cx_freeze ...
  260. self.app_home = os.path.dirname(os.path.realpath(__file__))
  261. App.log.debug("Application path is " + self.app_home)
  262. App.log.debug("Started in " + os.getcwd())
  263. # cx_freeze workaround
  264. if os.path.isfile(self.app_home):
  265. self.app_home = os.path.dirname(self.app_home)
  266. os.chdir(self.app_home)
  267. # #############################################################################
  268. # ##################### CREATE MULTIPROCESSING POOL ###########################
  269. # #############################################################################
  270. self.pool = Pool()
  271. # ##########################################################################
  272. # ################## Setting the Splash Screen #############################
  273. # ##########################################################################
  274. settings = QSettings("Open Source", "FlatCAM")
  275. if settings.contains("splash_screen"):
  276. show_splash = settings.value("splash_screen")
  277. else:
  278. settings.setValue('splash_screen', 1)
  279. # This will write the setting to the platform specific storage.
  280. del settings
  281. show_splash = 1
  282. if show_splash:
  283. splash_pix = QtGui.QPixmap('share/splash.png')
  284. splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  285. # splash.setMask(splash_pix.mask())
  286. splash.show()
  287. splash.showMessage(_("FlatCAM is initializing ..."),
  288. alignment=Qt.AlignBottom | Qt.AlignLeft,
  289. color=QtGui.QColor("gray"))
  290. # #############################################################################
  291. # ##################### Initialize GUI ########################################
  292. # #############################################################################
  293. # FlatCAM colors used in plotting
  294. self.FC_light_green = '#BBF268BF'
  295. self.FC_dark_green = '#006E20BF'
  296. self.FC_light_blue = '#a5a5ffbf'
  297. self.FC_dark_blue = '#0000ffbf'
  298. QtCore.QObject.__init__(self)
  299. self.ui = FlatCAMGUI(self.version, self.beta, self)
  300. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  301. self.ui.final_save.connect(self.final_save)
  302. # #############################################################################
  303. # ############################## Data #########################################
  304. # #############################################################################
  305. self.recent = []
  306. self.recent_projects = []
  307. self.clipboard = QtWidgets.QApplication.clipboard()
  308. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  309. self.project_filename = None
  310. self.toggle_units_ignore = False
  311. # self.defaults_form = PreferencesUI()
  312. # when adding entries here read the comments in the method found bellow named:
  313. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  314. self.defaults_form_fields = {
  315. # General App
  316. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  317. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  318. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  319. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  320. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  321. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  322. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  323. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  324. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  325. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  326. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  327. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  328. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  329. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  330. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  331. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  332. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  333. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  334. # General GUI Preferences
  335. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  336. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  337. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  338. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  339. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  340. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  341. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  342. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  343. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  344. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  345. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  346. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  347. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  348. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  349. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  350. # General GUI Settings
  351. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  352. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  353. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  354. # Gerber General
  355. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  356. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  357. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  358. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  359. "gerber_buffering": self.ui.gerber_defaults_form.gerber_gen_group.buffering_radio,
  360. "gerber_simplification": self.ui.gerber_defaults_form.gerber_gen_group.simplify_cb,
  361. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_gen_group.simplification_tol_spinner,
  362. # Gerber Options
  363. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  364. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  365. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  366. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  367. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  368. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  369. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  370. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  371. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  372. # Gerber Advanced Options
  373. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  374. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  375. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  376. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  377. # Gerber Export
  378. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  379. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  380. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  381. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  382. # Gerber Editor
  383. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  384. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  385. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  386. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  387. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  388. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  389. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  390. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  391. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  392. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  393. "gerber_editor_circ_angle":
  394. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  395. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  396. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  397. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  398. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  399. # Excellon General
  400. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  401. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  402. "excellon_format_upper_in":
  403. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  404. "excellon_format_lower_in":
  405. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  406. "excellon_format_upper_mm":
  407. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  408. "excellon_format_lower_mm":
  409. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  410. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  411. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  412. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  413. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  414. # Excellon Options
  415. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  416. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  417. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  418. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  419. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  420. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  421. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  422. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  423. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  424. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  425. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  426. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  427. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  428. # Excellon Advanced Options
  429. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  430. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  431. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  432. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  433. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  434. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  435. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  436. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  437. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  438. # Excellon Export
  439. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  440. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  441. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  442. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  443. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  444. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  445. # Excellon Editor
  446. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  447. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  448. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  449. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  450. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  451. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  452. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  453. "excellon_editor_circ_angle":
  454. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  455. # Excellon Slots
  456. "excellon_editor_slot_direction":
  457. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  458. "excellon_editor_slot_angle":
  459. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  460. "excellon_editor_slot_length":
  461. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  462. # Excellon Slots
  463. "excellon_editor_slot_array_size":
  464. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  465. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  466. "excellon_editor_slot_lin_pitch":
  467. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  468. "excellon_editor_slot_lin_angle":
  469. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  470. "excellon_editor_slot_circ_dir":
  471. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  472. "excellon_editor_slot_circ_angle":
  473. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  474. # Geometry General
  475. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  476. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  477. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  478. # Geometry Options
  479. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  480. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  481. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  482. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  483. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  484. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  485. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  486. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  487. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  488. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  489. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  490. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  491. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  492. # Geometry Advanced Options
  493. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  494. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  495. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  496. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  497. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  498. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  499. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  500. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  501. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  502. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  503. # Geometry Editor
  504. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  505. # CNCJob General
  506. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  507. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  508. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  509. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  510. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  511. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  512. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  513. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  514. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  515. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  516. # CNC Job Options
  517. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  518. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  519. # CNC Job Advanced Options
  520. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  521. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  522. # NCC Tool
  523. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  524. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  525. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  526. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  527. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  528. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  529. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  530. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  531. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  532. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  533. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  534. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  535. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  536. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  537. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  538. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  539. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  540. # CutOut Tool
  541. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  542. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  543. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  544. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  545. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  546. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  547. # Paint Area Tool
  548. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  549. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  550. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  551. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  552. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  553. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  554. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  555. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  556. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  557. # 2-sided Tool
  558. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  559. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  560. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  561. # Film Tool
  562. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  563. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  564. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  565. # Panelize Tool
  566. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  567. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  568. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  569. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  570. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  571. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  572. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  573. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  574. # Calculators Tool
  575. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  576. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  577. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  578. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  579. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  580. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  581. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  582. # Transformations Tool
  583. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  584. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  585. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  586. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  587. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  588. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  589. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  590. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  591. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  592. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  593. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  594. # SolderPaste Dispensing Tool
  595. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  596. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  597. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  598. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  599. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  600. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  601. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  602. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  603. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  604. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  605. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  606. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  607. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  608. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  609. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  610. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  611. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  612. # file associations
  613. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  614. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  615. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  616. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  617. }
  618. # ############################
  619. # ### LOAD POSTPROCESSORS ####
  620. # ############################
  621. self.postprocessors = load_postprocessors(self)
  622. for name in list(self.postprocessors.keys()):
  623. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  624. if name.partition('_')[0] == 'Paste':
  625. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  626. continue
  627. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  628. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  629. if name == 'hpgl':
  630. continue
  631. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  632. # ############################
  633. # ### LOAD LANGUAGES ####
  634. # ############################
  635. self.languages = fcTranslate.load_languages()
  636. for name in sorted(self.languages.values()):
  637. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  638. self.defaults = LoudDict()
  639. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  640. self.defaults.update({
  641. # Global APP Preferences
  642. "first_run": True,
  643. "units": "IN",
  644. "global_serial": 0,
  645. "global_stats": {},
  646. "global_tabs_detachable": True,
  647. "global_app_level": 'b',
  648. "global_portable": False,
  649. "global_language": 'English',
  650. "global_version_check": True,
  651. "global_send_stats": True,
  652. "global_pan_button": '2',
  653. "global_mselect_key": 'Control',
  654. "global_project_at_startup": False,
  655. "global_project_autohide": True,
  656. "global_toggle_tooltips": True,
  657. "global_worker_number": 2,
  658. "global_tolerance": 0.01,
  659. "global_open_style": True,
  660. "global_delete_confirmation": True,
  661. "global_compression_level": 3,
  662. "global_save_compressed": True,
  663. # Global GUI Preferences
  664. "global_gridx": 0.0393701,
  665. "global_gridy": 0.0393701,
  666. "global_snap_max": 0.001968504,
  667. "global_workspace": False,
  668. "global_workspaceT": "A4P",
  669. "global_grid_context_menu": {
  670. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  671. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  672. },
  673. "global_plot_fill": '#BBF268BF',
  674. "global_plot_line": '#006E20BF',
  675. "global_sel_fill": '#a5a5ffbf',
  676. "global_sel_line": '#0000ffbf',
  677. "global_alt_sel_fill": '#BBF268BF',
  678. "global_alt_sel_line": '#006E20BF',
  679. "global_draw_color": '#FF0000',
  680. "global_sel_draw_color": '#0000FF',
  681. "global_proj_item_color": '#000000',
  682. "global_proj_item_dis_color": '#b7b7cb',
  683. "global_toolbar_view": 511,
  684. "global_background_timeout": 300000, # Default value is 5 minutes
  685. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  686. # (python trace only for unknown errors),
  687. # 1 = show trace(show trace always),
  688. # 2 = (For the future).
  689. # Persistence
  690. "global_last_folder": None,
  691. "global_last_save_folder": None,
  692. # Default window geometry
  693. "global_def_win_x": 100,
  694. "global_def_win_y": 100,
  695. "global_def_win_w": 1024,
  696. "global_def_win_h": 650,
  697. "global_def_notebook_width": 1,
  698. # Constants...
  699. "global_defaults_save_period_ms": 20000, # Time between default saves.
  700. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  701. "global_shell_at_startup": False, # Show the shell at startup.
  702. "global_recent_limit": 10, # Max. items in recent list.
  703. "fit_key": 'V',
  704. "zoom_out_key": '-',
  705. "zoom_in_key": '=',
  706. "grid_toggle_key": 'G',
  707. "global_zoom_ratio": 1.5,
  708. "global_point_clipboard_format": "(%.4f, %.4f)",
  709. "global_zdownrate": None,
  710. # General GUI Settings
  711. "global_hover": False,
  712. "global_selection_shape": True,
  713. "global_layout": "compact",
  714. # Gerber General
  715. "gerber_plot": True,
  716. "gerber_solid": True,
  717. "gerber_multicolored": False,
  718. "gerber_circle_steps": 128,
  719. "gerber_use_buffer_for_union": True,
  720. "gerber_buffering": "full",
  721. "gerber_simplification": False,
  722. "gerber_simp_tolerance": 0.0005,
  723. # Gerber Options
  724. "gerber_isotooldia": 0.00787402,
  725. "gerber_isopasses": 1,
  726. "gerber_isooverlap": 0.00393701,
  727. "gerber_milling_type": "cl",
  728. "gerber_combine_passes": False,
  729. "gerber_noncoppermargin": 0.00393701,
  730. "gerber_noncopperrounded": False,
  731. "gerber_bboxmargin": 0.00393701,
  732. "gerber_bboxrounded": False,
  733. # Gerber Advanced Options
  734. "gerber_aperture_display": False,
  735. "gerber_aperture_scale_factor": 1.0,
  736. "gerber_aperture_buffer_factor": 0.0,
  737. "gerber_follow": False,
  738. # Gerber Export
  739. "gerber_exp_units": 'IN',
  740. "gerber_exp_integer": 2,
  741. "gerber_exp_decimals": 4,
  742. "gerber_exp_zeros": 'L',
  743. # Gerber Editor
  744. "gerber_editor_sel_limit": 30,
  745. "gerber_editor_newcode": 10,
  746. "gerber_editor_newsize": 0.8,
  747. "gerber_editor_newtype": 'C',
  748. "gerber_editor_newdim": "0.5, 0.5",
  749. "gerber_editor_array_size": 5,
  750. "gerber_editor_lin_axis": 'X',
  751. "gerber_editor_lin_pitch": 1,
  752. "gerber_editor_lin_angle": 0.0,
  753. "gerber_editor_circ_dir": 'CW',
  754. "gerber_editor_circ_angle": 0.0,
  755. "gerber_editor_scale_f": 1.0,
  756. "gerber_editor_buff_f": 0.1,
  757. "gerber_editor_ma_low": 0.0,
  758. "gerber_editor_ma_high": 1.0,
  759. # Excellon General
  760. "excellon_plot": True,
  761. "excellon_solid": True,
  762. "excellon_format_upper_in": 2,
  763. "excellon_format_lower_in": 4,
  764. "excellon_format_upper_mm": 3,
  765. "excellon_format_lower_mm": 3,
  766. "excellon_zeros": "L",
  767. "excellon_units": "INCH",
  768. "excellon_optimization_type": 'B',
  769. "excellon_search_time": 3,
  770. # Excellon Options
  771. "excellon_drillz": -0.0590551,
  772. "excellon_travelz": 0.0787402,
  773. "excellon_feedrate": 3.14961,
  774. "excellon_spindlespeed": None,
  775. "excellon_spindledir": 'CW',
  776. "excellon_dwell": False,
  777. "excellon_dwelltime": 1,
  778. "excellon_toolchange": False,
  779. "excellon_toolchangez": 0.5,
  780. "excellon_ppname_e": 'default',
  781. "excellon_tooldia": 0.0314961,
  782. "excellon_slot_tooldia": 0.0708661,
  783. "excellon_gcode_type": "drills",
  784. # Excellon Advanced Options
  785. "excellon_offset": 0.0,
  786. "excellon_toolchangexy": "0.0, 0.0",
  787. "excellon_startz": None,
  788. "excellon_endz": 0.5,
  789. "excellon_feedrate_rapid": 31.4961,
  790. "excellon_z_pdepth": -0.02,
  791. "excellon_feedrate_probe": 3.14961,
  792. "excellon_f_plunge": False,
  793. "excellon_f_retract": False,
  794. # Excellon Export
  795. "excellon_exp_units": 'INCH',
  796. "excellon_exp_format": 'ndec',
  797. "excellon_exp_integer": 2,
  798. "excellon_exp_decimals": 4,
  799. "excellon_exp_zeros": 'LZ',
  800. "excellon_exp_slot_type": 'routing',
  801. # Excellon Editor
  802. "excellon_editor_sel_limit": 30,
  803. "excellon_editor_newdia": 0.039,
  804. "excellon_editor_array_size": 5,
  805. "excellon_editor_lin_dir": 'X',
  806. "excellon_editor_lin_pitch": 0.1,
  807. "excellon_editor_lin_angle": 0.0,
  808. "excellon_editor_circ_dir": 'CW',
  809. "excellon_editor_circ_angle": 12,
  810. # Excellon Slots
  811. "excellon_editor_slot_direction": 'X',
  812. "excellon_editor_slot_angle": 0.0,
  813. "excellon_editor_slot_length": 5.0,
  814. # Excellon Slot Array
  815. "excellon_editor_slot_array_size": 5,
  816. "excellon_editor_slot_lin_dir": 'X',
  817. "excellon_editor_slot_lin_pitch": 0.1,
  818. "excellon_editor_slot_lin_angle": 0.0,
  819. "excellon_editor_slot_circ_dir": 'CW',
  820. "excellon_editor_slot_circ_angle": 0.0,
  821. # Geometry General
  822. "geometry_plot": True,
  823. "geometry_circle_steps": 128,
  824. "geometry_cnctooldia": "0.0944882",
  825. # Geometry Options
  826. "geometry_cutz": -0.0944882,
  827. "geometry_vtipdia": 0.1,
  828. "geometry_vtipangle": 30,
  829. "geometry_multidepth": False,
  830. "geometry_depthperpass": 0.0314961,
  831. "geometry_travelz": 0.0787402,
  832. "geometry_toolchange": False,
  833. "geometry_toolchangez": 0.5,
  834. "geometry_feedrate": 3.14961,
  835. "geometry_feedrate_z": 3.14961,
  836. "geometry_spindlespeed": None,
  837. "geometry_spindledir": 'CW',
  838. "geometry_dwell": False,
  839. "geometry_dwelltime": 1,
  840. "geometry_ppname_g": 'default',
  841. # Geometry Advanced Options
  842. "geometry_toolchangexy": "0.0, 0.0",
  843. "geometry_startz": None,
  844. "geometry_endz": 0.5,
  845. "geometry_feedrate_rapid": 3.14961,
  846. "geometry_extracut": False,
  847. "geometry_z_pdepth": -0.02,
  848. "geometry_f_plunge": False,
  849. "geometry_feedrate_probe": 3.14961,
  850. "geometry_segx": 0.0,
  851. "geometry_segy": 0.0,
  852. # Geometry Editor
  853. "geometry_editor_sel_limit": 30,
  854. # CNC Job General
  855. "cncjob_plot": True,
  856. "cncjob_plot_kind": 'all',
  857. "cncjob_annotation": True,
  858. "cncjob_annotation_fontsize": 9,
  859. "cncjob_annotation_fontcolor": '#990000',
  860. "cncjob_tooldia": 0.0393701,
  861. "cncjob_coords_type": "G90",
  862. "cncjob_coords_decimals": 4,
  863. "cncjob_fr_decimals": 2,
  864. "cncjob_steps_per_circle": 128,
  865. # CNC Job Options
  866. "cncjob_prepend": "",
  867. "cncjob_append": "",
  868. # CNC Job Advanced Options
  869. "cncjob_toolchange_macro": "",
  870. "cncjob_toolchange_macro_enable": False,
  871. "tools_ncctools": "0.0393701, 0.019685",
  872. "tools_nccorder": 'rev',
  873. "tools_nccoverlap": 0.015748,
  874. "tools_nccmargin": 0.0393701,
  875. "tools_nccmethod": "seed",
  876. "tools_nccconnect": True,
  877. "tools_ncccontour": True,
  878. "tools_nccrest": False,
  879. "tools_ncc_offset_choice": False,
  880. "tools_ncc_offset_value": 0.0000,
  881. "tools_nccref": 'itself',
  882. "tools_ncc_plotting": 'normal',
  883. "tools_nccmilling_type": 'cl',
  884. "tools_ncctool_type": 'V',
  885. "tools_ncccutz": -0.001968504,
  886. "tools_ncctipdia": 0.00393701,
  887. "tools_ncctipangle": 30,
  888. "tools_cutouttooldia": 0.0944882,
  889. "tools_cutoutkind": "single",
  890. "tools_cutoutmargin": 0.00393701,
  891. "tools_cutoutgapsize": 0.15748,
  892. "tools_gaps_ff": "4",
  893. "tools_cutout_convexshape": False,
  894. "tools_painttooldia": 0.023622,
  895. "tools_paintorder": 'rev',
  896. "tools_paintoverlap": 0.015748,
  897. "tools_paintmargin": 0.0,
  898. "tools_paintmethod": "seed",
  899. "tools_selectmethod": "single",
  900. "tools_pathconnect": True,
  901. "tools_paintcontour": True,
  902. "tools_paint_plotting": 'normal',
  903. "tools_2sided_mirror_axis": "X",
  904. "tools_2sided_axis_loc": "point",
  905. "tools_2sided_drilldia": 0.0393701,
  906. "tools_film_type": 'neg',
  907. "tools_film_boundary": 0.0393701,
  908. "tools_film_scale": 0,
  909. "tools_panelize_spacing_columns": 0,
  910. "tools_panelize_spacing_rows": 0,
  911. "tools_panelize_columns": 1,
  912. "tools_panelize_rows": 1,
  913. "tools_panelize_constrain": False,
  914. "tools_panelize_constrainx": 0.0,
  915. "tools_panelize_constrainy": 0.0,
  916. "tools_panelize_panel_type": 'gerber',
  917. "tools_calc_vshape_tip_dia": 0.007874,
  918. "tools_calc_vshape_tip_angle": 30,
  919. "tools_calc_vshape_cut_z": 0.000787,
  920. "tools_calc_electro_length": 10.0,
  921. "tools_calc_electro_width": 10.0,
  922. "tools_calc_electro_cdensity": 13.0,
  923. "tools_calc_electro_growth": 10.0,
  924. "tools_transform_rotate": 90,
  925. "tools_transform_skew_x": 0.0,
  926. "tools_transform_skew_y": 0.0,
  927. "tools_transform_scale_x": 1.0,
  928. "tools_transform_scale_y": 1.0,
  929. "tools_transform_scale_link": True,
  930. "tools_transform_scale_reference": True,
  931. "tools_transform_offset_x": 0.0,
  932. "tools_transform_offset_y": 0.0,
  933. "tools_transform_mirror_reference": False,
  934. "tools_transform_mirror_point": (0, 0),
  935. "tools_solderpaste_tools": "0.0393701, 0.011811",
  936. "tools_solderpaste_new": 0.011811,
  937. "tools_solderpaste_z_start": 0.00019685039,
  938. "tools_solderpaste_z_dispense": 0.00393701,
  939. "tools_solderpaste_z_stop": 0.00019685039,
  940. "tools_solderpaste_z_travel": 0.00393701,
  941. "tools_solderpaste_z_toolchange": 0.0393701,
  942. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  943. "tools_solderpaste_frxy": 3.0,
  944. "tools_solderpaste_frz": 3.0,
  945. "tools_solderpaste_frz_dispense": 0.0393701,
  946. "tools_solderpaste_speedfwd": 20,
  947. "tools_solderpaste_dwellfwd": 1,
  948. "tools_solderpaste_speedrev": 10,
  949. "tools_solderpaste_dwellrev": 1,
  950. "tools_solderpaste_pp": 'Paste_1',
  951. "tools_sub_close_paths": True,
  952. # file associations
  953. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  954. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  955. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  956. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  957. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  958. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  959. })
  960. # ############################################################
  961. # ############### Load defaults from file ####################
  962. # ############################################################
  963. if user_defaults:
  964. self.load_defaults(filename='current_defaults')
  965. # #############################################################
  966. # ############## APPLY APP LANGUAGE ###########################
  967. # #############################################################
  968. ret_val = fcTranslate.apply_language('strings')
  969. if ret_val == "no language":
  970. self.inform.emit('[ERROR] %s' %
  971. _("Could not find the Language files. The App strings are missing."))
  972. log.debug("Could not find the Language files. The App strings are missing.")
  973. else:
  974. # make the current language the current selection on the language combobox
  975. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  976. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  977. # ##############################################################
  978. # ################# CREATE UNIQUE SERIAL NUMBER ################
  979. # ##############################################################
  980. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  981. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  982. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  983. self.save_defaults(silent=True)
  984. self.propagate_defaults(silent=True)
  985. self.restore_main_win_geom()
  986. def auto_save_defaults():
  987. try:
  988. self.save_defaults(silent=True)
  989. self.propagate_defaults(silent=True)
  990. finally:
  991. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  992. # the following lines activates automatic defaults save
  993. # if user_defaults:
  994. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  995. # self.options_form = PreferencesUI()
  996. self.options_form_fields = {
  997. "units": self.ui.general_options_form.general_app_group.units_radio,
  998. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  999. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1000. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1001. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1002. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1003. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1004. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1005. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1006. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1007. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1008. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1009. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1010. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1011. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1012. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1013. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1014. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1015. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1016. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1017. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1018. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1019. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1020. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1021. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1022. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1023. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1024. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1025. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  1026. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1027. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1028. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1029. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1030. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1031. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1032. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1033. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1034. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1035. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1036. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  1037. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1038. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1039. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1040. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1041. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1042. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1043. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1044. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  1045. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1046. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1047. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1048. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1049. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1050. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1051. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1052. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1053. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1054. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1055. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1056. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1057. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1058. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  1059. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1060. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1061. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1062. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1063. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1064. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1065. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1066. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1067. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1068. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1069. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1070. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1071. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1072. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1073. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1074. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1075. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1076. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1077. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1078. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1079. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1080. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1081. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1082. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1083. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1084. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1085. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1086. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1087. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1088. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1089. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1090. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1091. }
  1092. for name in list(self.postprocessors.keys()):
  1093. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1094. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1095. self.options = LoudDict()
  1096. self.options.set_change_callback(self.on_options_dict_change)
  1097. self.options.update({
  1098. "units": "IN",
  1099. "global_gridx": 1.0,
  1100. "global_gridy": 1.0,
  1101. "global_snap_max": 0.05,
  1102. "global_background_timeout": 300000, # Default value is 5 minutes
  1103. "global_verbose_error_level": 0, # Shell verbosity:
  1104. # 0 = default(python trace only for unknown errors),
  1105. # 1 = show trace(show trace allways), 2 = (For the future).
  1106. "gerber_plot": True,
  1107. "gerber_solid": True,
  1108. "gerber_multicolored": False,
  1109. "gerber_isotooldia": 0.016,
  1110. "gerber_isopasses": 1,
  1111. "gerber_isooverlap": 0.15,
  1112. "gerber_combine_passes": True,
  1113. "gerber_noncoppermargin": 0.0,
  1114. "gerber_noncopperrounded": False,
  1115. "gerber_bboxmargin": 0.0,
  1116. "gerber_bboxrounded": False,
  1117. "excellon_plot": True,
  1118. "excellon_solid": False,
  1119. "excellon_format_upper_in": 2,
  1120. "excellon_format_lower_in": 4,
  1121. "excellon_format_upper_mm": 3,
  1122. "excellon_format_lower_mm": 3,
  1123. "excellon_units": 'INCH',
  1124. "excellon_optimization_type": 'B',
  1125. "excellon_search_time": 3,
  1126. "excellon_zeros": "L",
  1127. "excellon_drillz": -0.1,
  1128. "excellon_travelz": 0.1,
  1129. "excellon_feedrate": 3.0,
  1130. "excellon_feedrate_rapid": 3.0,
  1131. "excellon_spindlespeed": None,
  1132. "excellon_spindledir": 'CW',
  1133. "excellon_dwell": True,
  1134. "excellon_dwelltime": 1000,
  1135. "excellon_toolchange": False,
  1136. "excellon_toolchangez": 1.0,
  1137. "excellon_toolchangexy": "0.0, 0.0",
  1138. "excellon_tooldia": 0.016,
  1139. "excellon_ppname_e": 'default',
  1140. "excellon_f_plunge": False,
  1141. "excellon_startz": None,
  1142. "excellon_endz": 2.0,
  1143. "geometry_plot": True,
  1144. "geometry_segx": 0.0,
  1145. "geometry_segy": 0.0,
  1146. "geometry_cutz": -0.002,
  1147. "geometry_vtipdia": 0.1,
  1148. "geometry_vtipangle": 30,
  1149. "geometry_travelz": 0.1,
  1150. "geometry_feedrate": 3.0,
  1151. "geometry_feedrate_z": 3.0,
  1152. "geometry_feedrate_rapid": 3.0,
  1153. "geometry_spindlespeed": None,
  1154. "geometry_spindledir": 'CW',
  1155. "geometry_dwell": True,
  1156. "geometry_dwelltime": 1000,
  1157. "geometry_cnctooldia": 0.016,
  1158. "geometry_toolchange": False,
  1159. "geometry_toolchangez": 2.0,
  1160. "geometry_toolchangexy": "0.0, 0.0",
  1161. "geometry_startz": None,
  1162. "geometry_endz": 2.0,
  1163. "geometry_ppname_g": "default",
  1164. "geometry_f_plunge": False,
  1165. "geometry_depthperpass": 0.002,
  1166. "geometry_multidepth": False,
  1167. "geometry_extracut": False,
  1168. "cncjob_plot": True,
  1169. "cncjob_tooldia": 0.016,
  1170. "cncjob_prepend": "",
  1171. "cncjob_append": "",
  1172. "tools_ncctools": "1.0, 0.5",
  1173. "tools_nccoverlap": 0.4,
  1174. "tools_nccmargin": 1,
  1175. "tools_cutouttooldia": 0.07,
  1176. "tools_cutoutmargin": 0.1,
  1177. "tools_cutoutgapsize": 0.15,
  1178. "tools_gaps_ff": "8",
  1179. "tools_painttooldia": 0.07,
  1180. "tools_paintoverlap": 0.15,
  1181. "tools_paintmargin": 0.0,
  1182. "tools_paintmethod": "seed",
  1183. "tools_selectmethod": "single",
  1184. "tools_pathconnect": True,
  1185. "tools_paintcontour": True,
  1186. "tools_2sided_mirror_axis": "X",
  1187. "tools_2sided_axis_loc": 'point',
  1188. "tools_2sided_drilldia": 1,
  1189. "tools_film_type": 'neg',
  1190. "tools_film_boundary": 1,
  1191. "tools_film_scale": 0,
  1192. "tools_panelize_spacing_columns": 0,
  1193. "tools_panelize_spacing_rows": 0,
  1194. "tools_panelize_columns": 1,
  1195. "tools_panelize_rows": 1,
  1196. "tools_panelize_constrain": False,
  1197. "tools_panelize_constrainx": 0.0,
  1198. "tools_panelize_constrainy": 0.0
  1199. })
  1200. self.options.update(self.defaults) # Copy app defaults to project options
  1201. self.gen_form = None
  1202. self.ger_form = None
  1203. self.exc_form = None
  1204. self.geo_form = None
  1205. self.cnc_form = None
  1206. self.tools_form = None
  1207. self.fa_form = None
  1208. self.on_options_combo_change(0) # Will show the initial form
  1209. # ################################
  1210. # ### Initialize the color box's color in Preferences -> Global -> Color
  1211. # Init Plot Colors
  1212. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1213. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1214. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1215. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1216. int(self.defaults['global_plot_fill'][7:9], 16))
  1217. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1218. int(self.defaults['global_plot_fill'][7:9], 16))
  1219. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1220. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1221. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1222. # Init Left-Right Selection colors
  1223. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1224. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1225. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1226. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1227. int(self.defaults['global_sel_fill'][7:9], 16))
  1228. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1229. int(self.defaults['global_sel_fill'][7:9], 16))
  1230. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1231. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1232. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1233. # Init Right-Left Selection colors
  1234. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1235. self.defaults['global_alt_sel_fill'])
  1236. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1237. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1238. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1239. int(self.defaults['global_sel_fill'][7:9], 16))
  1240. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1241. int(self.defaults['global_sel_fill'][7:9], 16))
  1242. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1243. self.defaults['global_alt_sel_line'])
  1244. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1245. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1246. # Init Draw color and Selection Draw Color
  1247. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1248. self.defaults['global_draw_color'])
  1249. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1250. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1251. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1252. self.defaults['global_sel_draw_color'])
  1253. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1254. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1255. # Init Project Items color
  1256. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1257. self.defaults['global_proj_item_color'])
  1258. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1259. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1260. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1261. self.defaults['global_proj_item_dis_color'])
  1262. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1263. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1264. # Init the Annotation CNC Job color
  1265. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1266. self.defaults['cncjob_annotation_fontcolor'])
  1267. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1268. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1269. # ### End of Data ####
  1270. # ###############################################
  1271. # ############# SETUP Plot Area #################
  1272. # ###############################################
  1273. if show_splash:
  1274. splash.showMessage(_("FlatCAM is initializing ...\n"
  1275. "Canvas initialization started."),
  1276. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1277. color=QtGui.QColor("gray"))
  1278. start_plot_time = time.time() # debug
  1279. self.plotcanvas = None
  1280. self.app_cursor = None
  1281. self.hover_shapes = None
  1282. self.on_plotcanvas_setup()
  1283. end_plot_time = time.time()
  1284. used_time = end_plot_time - start_plot_time
  1285. self.log.debug("Finished Canvas initialization in %s seconds." % str(used_time))
  1286. if show_splash:
  1287. splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1288. "Canvas initialization started.\n"
  1289. "Canvas initialization finished in"), '%.2f' % used_time),
  1290. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1291. color=QtGui.QColor("gray"))
  1292. self.ui.splitter.setStretchFactor(1, 2)
  1293. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1294. # depending on from where those tools are called different actions can be done
  1295. self.call_source = 'app'
  1296. # ##############################################
  1297. # ######### SETUP OBJECT COLLECTION ############
  1298. # ##############################################
  1299. self.collection = ObjectCollection(self)
  1300. self.ui.project_tab_layout.addWidget(self.collection.view)
  1301. # ### Adjust tabs width ## ##
  1302. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1303. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1304. self.collection.view.setMinimumWidth(290)
  1305. self.log.debug("Finished creating Object Collection.")
  1306. # ###############################################
  1307. # ############# Worker SETUP ####################
  1308. # ###############################################
  1309. if self.defaults["global_worker_number"]:
  1310. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1311. else:
  1312. self.workers = WorkerStack(workers_number=2)
  1313. self.worker_task.connect(self.workers.add_task)
  1314. self.log.debug("Finished creating Workers crew.")
  1315. # ################################################
  1316. # ############### Signal handling ################
  1317. # ################################################
  1318. # ############# Custom signals ##################
  1319. # signal for displaying messages in status bar
  1320. self.inform.connect(self.info)
  1321. # signal to be called when the app is quiting
  1322. self.app_quit.connect(self.quit_application)
  1323. self.message.connect(self.message_dialog)
  1324. self.progress.connect(self.set_progress_bar)
  1325. # signals that are emitted when object state changes
  1326. self.object_created.connect(self.on_object_created)
  1327. self.object_changed.connect(self.on_object_changed)
  1328. self.object_plotted.connect(self.on_object_plotted)
  1329. self.plots_updated.connect(self.on_plots_updated)
  1330. # signals emitted when file state change
  1331. self.file_opened.connect(self.register_recent)
  1332. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1333. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1334. # ############# Standard signals ###################
  1335. # ### Menu
  1336. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1337. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1338. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1339. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1340. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1341. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1342. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1343. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1344. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1345. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1346. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1347. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1348. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1349. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1350. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1351. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1352. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1353. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1354. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1355. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1356. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1357. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1358. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1359. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1360. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1361. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1362. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1363. self.ui.menufile_exit.triggered.connect(self.final_save)
  1364. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1365. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1366. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1367. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1368. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1369. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1370. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1371. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1372. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1373. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1374. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1375. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1376. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1377. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1378. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1379. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1380. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1381. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1382. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1383. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1384. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1385. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1386. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1387. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1388. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1389. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1390. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1391. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1392. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1393. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1394. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1395. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1396. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1397. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1398. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1399. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1400. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1401. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1402. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1403. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1404. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1405. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1406. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1407. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1408. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1409. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1410. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1411. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1412. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1413. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1414. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1415. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1416. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1417. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1418. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1419. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1420. # ToolBar signals
  1421. self.connect_toolbar_signals()
  1422. # Notebook signals
  1423. # make the right click on the notebook tab connect to a function
  1424. self.ui.notebook.setupContextMenu()
  1425. self.ui.notebook.addContextMenu(
  1426. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1427. initial_checked=self.defaults["global_tabs_detachable"])
  1428. # activate initial state
  1429. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1430. # Context Menu
  1431. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1432. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1433. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1434. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1435. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1436. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1437. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1438. self.ui.clearplot.triggered.connect(self.clear_plots)
  1439. self.ui.replot.triggered.connect(self.plot_all)
  1440. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1441. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1442. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1443. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1444. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1445. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1446. # Preferences Plot Area TAB
  1447. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1448. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1449. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1450. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1451. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1452. # ##############################
  1453. # ### GUI PREFERENCES SIGNALS ##
  1454. # ##############################
  1455. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1456. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1457. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1458. )
  1459. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1460. lambda: self.on_toggle_units(no_pref=False))
  1461. # ###############################################################
  1462. # ################### GUI COLORS SIGNALS ########################
  1463. # ###############################################################
  1464. # Setting plot colors signals
  1465. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1466. self.on_pf_color_entry)
  1467. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1468. self.on_pf_color_button)
  1469. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1470. self.on_pf_color_spinner)
  1471. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1472. self.on_pf_color_slider)
  1473. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1474. self.on_pl_color_entry)
  1475. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1476. self.on_pl_color_button)
  1477. # Setting selection (left - right) colors signals
  1478. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1479. self.on_sf_color_entry)
  1480. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1481. self.on_sf_color_button)
  1482. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1483. self.on_sf_color_spinner)
  1484. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1485. self.on_sf_color_slider)
  1486. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1487. self.on_sl_color_entry)
  1488. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1489. self.on_sl_color_button)
  1490. # Setting selection (right - left) colors signals
  1491. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1492. self.on_alt_sf_color_entry)
  1493. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1494. self.on_alt_sf_color_button)
  1495. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1496. self.on_alt_sf_color_spinner)
  1497. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1498. self.on_alt_sf_color_slider)
  1499. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1500. self.on_alt_sl_color_entry)
  1501. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1502. self.on_alt_sl_color_button)
  1503. # Setting Editor Draw colors signals
  1504. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1505. self.on_draw_color_entry)
  1506. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1507. self.on_draw_color_button)
  1508. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1509. self.on_sel_draw_color_entry)
  1510. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1511. self.on_sel_draw_color_button)
  1512. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1513. self.on_proj_color_entry)
  1514. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1515. self.on_proj_color_button)
  1516. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1517. self.on_proj_color_dis_entry)
  1518. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1519. self.on_proj_color_dis_button)
  1520. # ########## workspace setting signals ###########
  1521. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1522. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1523. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1524. # ########## CNC Job related signals #############
  1525. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1526. self.on_cnc_custom_parameters)
  1527. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1528. self.on_annotation_fontcolor_entry)
  1529. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1530. self.on_annotation_fontcolor_button)
  1531. # ########## Modify G-CODE Plot Area TAB ###########
  1532. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1533. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1534. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1535. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1536. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1537. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1538. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1539. # portability changed signal
  1540. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1541. # Object list
  1542. self.collection.view.activated.connect(self.on_row_activated)
  1543. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1544. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1545. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1546. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1547. self.on_excellon_defaults_button)
  1548. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1549. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1550. self.on_excellon_options_button)
  1551. # when there are arguments at application startup this get launched
  1552. self.args_at_startup[list].connect(lambda: self.on_startup_args())
  1553. # connect the 'Apply' buttons from the Preferences/File Associations
  1554. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1555. lambda: self.on_register_files(obj_type='excellon'))
  1556. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1557. lambda: self.on_register_files(obj_type='gcode'))
  1558. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1559. lambda: self.on_register_files(obj_type='gerber'))
  1560. # splash screen button signal
  1561. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1562. # connect the abort_all_tasks related slots to the related signals
  1563. self.proc_container.idle_flag.connect(self.app_is_idle)
  1564. # #####################################################################################
  1565. # ########### FINISHED CONNECTING SIGNALS #############################################
  1566. # #####################################################################################
  1567. self.log.debug("Finished connecting Signals.")
  1568. # #####################################################################################
  1569. # ########################## Other setups #############################################
  1570. # #####################################################################################
  1571. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1572. self.tool_tab_locked = False
  1573. # decide if to show or hide the Notebook side of the screen at startup
  1574. if self.defaults["global_project_at_startup"] is True:
  1575. self.ui.splitter.setSizes([1, 1])
  1576. else:
  1577. self.ui.splitter.setSizes([0, 1])
  1578. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1579. self.setup_obj_classes()
  1580. self.setup_recent_items()
  1581. self.setup_component_editor()
  1582. # #####################################################################################
  1583. # ######################### Auto-complete KEYWORDS ####################################
  1584. # #####################################################################################
  1585. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1586. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1587. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1588. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1589. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1590. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1591. 'mirror', 'ncc',
  1592. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1593. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1594. 'pan', 'panel', 'panelize', 'plot', 'save', 'save_project', 'save_sys', 'scale',
  1595. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1596. 'version', 'write_gcode'
  1597. ]
  1598. self.ordinary_keywords = ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1599. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  1600. 'drilled_dias', 'drillz',
  1601. 'endz', 'extracut', 'factor', 'False', 'false', 'feedrate', 'feedrate_rapid',
  1602. 'filename', 'follow', 'gaps', 'gapsize', 'grid', 'gridoffset', 'gridoffsetx',
  1603. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1604. 'milled_dias',
  1605. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1606. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1607. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1608. 'toolchange', 'toolchangez', 'tooldia', 'tools', 'travelz', 'True', 'true', 'type',
  1609. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1610. ]
  1611. self.tcl_keywords = [
  1612. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1613. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1614. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1615. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1616. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1617. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1618. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1619. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1620. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1621. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1622. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1623. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1624. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1625. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1626. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1627. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1628. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1629. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1630. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1631. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1632. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1633. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1634. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1635. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1636. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1637. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1638. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1639. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1640. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1641. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1642. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1643. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1644. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1645. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1646. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1647. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1648. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1649. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1650. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1651. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1652. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1653. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1654. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1655. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1656. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1657. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1658. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1659. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1660. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1661. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1662. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1663. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1664. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1665. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1666. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1667. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1668. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1669. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1670. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1671. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1672. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1673. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1674. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1675. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1676. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1677. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1678. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1679. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1680. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1681. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1682. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1683. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1684. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1685. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1686. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1687. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1688. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1689. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1690. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1691. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1692. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1693. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1694. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1695. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1696. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1697. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1698. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1699. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1700. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1701. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1702. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1703. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1704. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1705. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1706. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1707. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1708. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1709. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1710. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1711. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1712. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1713. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1714. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1715. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1716. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1717. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1718. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1719. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1720. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1721. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1722. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1723. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1724. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1725. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1726. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1727. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1728. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1729. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1730. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1731. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1732. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1733. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1734. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1735. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1736. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1737. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1738. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1739. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1740. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1741. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1742. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1743. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1744. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1745. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1746. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1747. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1748. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1749. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1750. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1751. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1752. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1753. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1754. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1755. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1756. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1757. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1758. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1759. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1760. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1761. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1762. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1763. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1764. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1765. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1766. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1767. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1768. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1769. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1770. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1771. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1772. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1773. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1774. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1775. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1776. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1777. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1778. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1779. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1780. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1781. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1782. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1783. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1784. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1785. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1786. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1787. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1788. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1789. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1790. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1791. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1792. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1793. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1794. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1795. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1796. ]
  1797. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1798. # ####################################################################################
  1799. # ####################### Shell SETUP ################################################
  1800. # ####################################################################################
  1801. self.shell = FCShell(self, version=self.version)
  1802. self.shell._edit.set_model_data(self.myKeywords)
  1803. self.ui.code_editor.set_model_data(self.myKeywords)
  1804. self.shell.setWindowIcon(self.ui.app_icon)
  1805. self.shell.setWindowTitle("FlatCAM Shell")
  1806. self.shell.resize(*self.defaults["global_shell_shape"])
  1807. self.shell.append_output("FlatCAM %s - " % self.version)
  1808. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1809. self.init_tcl()
  1810. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1811. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1812. self.ui.shell_dock.setWidget(self.shell)
  1813. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1814. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1815. QtWidgets.QDockWidget.DockWidgetFloatable |
  1816. QtWidgets.QDockWidget.DockWidgetClosable)
  1817. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1818. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1819. if self.defaults["global_shell_at_startup"]:
  1820. self.ui.shell_dock.show()
  1821. else:
  1822. self.ui.shell_dock.hide()
  1823. # ##################################################################################
  1824. # ###################### Tools and Plugins #########################################
  1825. # ##################################################################################
  1826. self.dblsidedtool = None
  1827. self.measurement_tool = None
  1828. self.panelize_tool = None
  1829. self.film_tool = None
  1830. self.paste_tool = None
  1831. self.calculator_tool = None
  1832. self.sub_tool = None
  1833. self.move_tool = None
  1834. self.cutout_tool = None
  1835. self.ncclear_tool = None
  1836. self.paint_tool = None
  1837. self.transform_tool = None
  1838. self.properties_tool = None
  1839. self.pdf_tool = None
  1840. self.image_tool = None
  1841. self.pcb_wizard_tool = None
  1842. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1843. self.install_tools()
  1844. # ### System Font Parsing ###
  1845. # self.f_parse = ParseFont(self)
  1846. # self.parse_system_fonts()
  1847. # #####################################################################################
  1848. # ########################## START-UP ARGUMENTS #######################################
  1849. # #####################################################################################
  1850. # test if the program was started with a script as parameter
  1851. if self.cmd_line_shellfile:
  1852. try:
  1853. with open(self.cmd_line_shellfile, "r") as myfile:
  1854. cmd_line_shellfile_text = myfile.read()
  1855. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1856. except Exception as ext:
  1857. print("ERROR: ", ext)
  1858. sys.exit(2)
  1859. # #####################################################################################
  1860. # ######################## Check for updates ##########################################
  1861. # #####################################################################################
  1862. # Separate thread (Not worker)
  1863. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1864. if (self.beta is False or self.beta is None) and \
  1865. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1866. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1867. self.thr2 = QtCore.QThread()
  1868. self.worker_task.emit({'fcn': self.version_check,
  1869. 'params': []})
  1870. self.thr2.start(QtCore.QThread.LowPriority)
  1871. # #####################################################################################
  1872. # ###################### Variables for global usage ###################################
  1873. # #####################################################################################
  1874. # register files with FlatCAM; it works only for Windows for now
  1875. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1876. self.on_register_files()
  1877. # coordinates for relative position display
  1878. self.rel_point1 = (0, 0)
  1879. self.rel_point2 = (0, 0)
  1880. # variable to store coordinates
  1881. self.pos = (0, 0)
  1882. self.pos_jump = (0, 0)
  1883. # variable to store mouse coordinates
  1884. self.mouse = [0, 0]
  1885. # decide if we have a double click or single click
  1886. self.doubleclick = False
  1887. # variable to store if a command is active (then the var is not None) and which one it is
  1888. self.command_active = None
  1889. # variable to store the status of moving selection action
  1890. # None value means that it's not an selection action
  1891. # True value = a selection from left to right
  1892. # False value = a selection from right to left
  1893. self.selection_type = None
  1894. # List to store the objects that are currently loaded in FlatCAM
  1895. # This list is updated on each object creation or object delete
  1896. self.all_objects_list = []
  1897. # List to store the objects that are selected
  1898. self.sel_objects_list = []
  1899. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1900. self.key_modifiers = None
  1901. # Variable to hold the status of the axis
  1902. self.toggle_axis = True
  1903. # Variable to store the status of the fullscreen event
  1904. self.toggle_fscreen = False
  1905. # Variable to store the status of the code editor
  1906. self.toggle_codeeditor = False
  1907. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1908. self.click_noproject = False
  1909. self.cursor = None
  1910. # Variable to store the GCODE that was edited
  1911. self.gcode_edited = ""
  1912. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1913. self.preferences_changed_flag = False
  1914. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1915. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1916. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1917. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1918. ]
  1919. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1920. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1921. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1922. 'mpf'
  1923. ]
  1924. self.svg_list = ['svg']
  1925. self.dxf_list = ['dxf']
  1926. self.pdf_list = ['pdf']
  1927. self.prj_list = ['flatprj']
  1928. self.conf_list = ['flatconfig']
  1929. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1930. # flag for polygons not cleared
  1931. self.poly_not_cleared = False
  1932. # VisPy visuals
  1933. self.isHovering = False
  1934. self.notHovering = True
  1935. # when True, the app has to return from any thread
  1936. self.abort_flag = False
  1937. # ###############################################################################
  1938. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  1939. # ############# It's done only once after install ###############
  1940. # ###############################################################################
  1941. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1942. fac_def_from_file = factory_file.read()
  1943. factory_defaults = json.loads(fac_def_from_file)
  1944. # if the file contain an empty dictionary then save the factory defaults into the file
  1945. if not factory_defaults:
  1946. self.save_factory_defaults(silent=False)
  1947. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1948. initial_lay = 'compact'
  1949. self.on_layout(lay=initial_lay)
  1950. # Set the combobox in Preferences to the current layout
  1951. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1952. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1953. factory_file.close()
  1954. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1955. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1956. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1957. # after the first run, this object should be False
  1958. self.defaults["first_run"] = False
  1959. # ###############################################################################
  1960. # ################# ADDING FlatCAM EDITORS section ##############################
  1961. # ###############################################################################
  1962. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1963. # at the first launch of the App , the editors will not be functional.
  1964. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1965. self.exc_editor = FlatCAMExcEditor(self)
  1966. self.grb_editor = FlatCAMGrbEditor(self)
  1967. self.log.debug("Finished adding FlatCAM Editor's.")
  1968. self.set_ui_title(name=_("New Project - Not saved"))
  1969. # ###############################################################################
  1970. # ####################### Finished the CONSTRUCTOR ##############################
  1971. # ###############################################################################
  1972. App.log.debug("END of constructor. Releasing control.")
  1973. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1974. # the path/file_name must be enclosed in quotes if it contain spaces
  1975. if App.args:
  1976. self.args_at_startup.emit(App.args)
  1977. @staticmethod
  1978. def copy_and_overwrite(from_path, to_path):
  1979. """
  1980. From here:
  1981. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1982. :param from_path: source path
  1983. :param to_path: destination path
  1984. :return: None
  1985. """
  1986. if os.path.exists(to_path):
  1987. shutil.rmtree(to_path)
  1988. try:
  1989. shutil.copytree(from_path, to_path)
  1990. except FileNotFoundError:
  1991. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1992. shutil.copytree(from_new_path, to_path)
  1993. def on_startup_args(self, args=None):
  1994. """
  1995. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1996. :param args: a list containing the application args at startup
  1997. :return: None
  1998. """
  1999. if args:
  2000. args_to_process = args
  2001. else:
  2002. args_to_process = App.args
  2003. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2004. for argument in args_to_process:
  2005. if '.FlatPrj' in argument:
  2006. try:
  2007. project_name = str(argument)
  2008. if project_name == "":
  2009. self.inform.emit(_("Open cancelled."))
  2010. else:
  2011. # self.open_project(project_name)
  2012. run_from_arg = True
  2013. # self.worker_task.emit({'fcn': self.open_project,
  2014. # 'params': [project_name, run_from_arg]})
  2015. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2016. except Exception as e:
  2017. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2018. elif '.FlatConfig' in argument:
  2019. try:
  2020. file_name = str(argument)
  2021. if file_name == "":
  2022. self.inform.emit(_("Open Config file failed."))
  2023. else:
  2024. # run_from_arg = True
  2025. # self.worker_task.emit({'fcn': self.open_config_file,
  2026. # 'params': [file_name, run_from_arg]})
  2027. self.open_config_file(file_name, run_from_arg=True)
  2028. except Exception as e:
  2029. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2030. elif '.FlatScript' in argument:
  2031. try:
  2032. file_name = str(argument)
  2033. if file_name == "":
  2034. self.inform.emit(_("Open Script file failed."))
  2035. else:
  2036. # run_from_arg = True
  2037. # self.worker_task.emit({'fcn': self.open_script_file,
  2038. # 'params': [file_name, run_from_arg]})
  2039. self.on_filerunscript(name=file_name)
  2040. except Exception as e:
  2041. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2042. else:
  2043. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2044. proc_arg = argument.lower()
  2045. for ext in exc_list:
  2046. proc_ext = ext.replace(' ', '')
  2047. if proc_ext.lower() in proc_arg and proc_ext != '':
  2048. file_name = str(argument)
  2049. if file_name == "":
  2050. self.inform.emit(_("Open Excellon file failed."))
  2051. else:
  2052. self.on_fileopenexcellon(name=file_name)
  2053. return
  2054. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2055. for ext in gco_list:
  2056. proc_ext = ext.replace(' ', '')
  2057. if proc_ext.lower() in proc_arg and proc_ext != '':
  2058. file_name = str(argument)
  2059. if file_name == "":
  2060. self.inform.emit(_("Open GCode file failed."))
  2061. else:
  2062. self.on_fileopengcode(name=file_name)
  2063. return
  2064. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2065. for ext in grb_list:
  2066. proc_ext = ext.replace(' ', '')
  2067. if proc_ext.lower() in proc_arg and proc_ext != '':
  2068. file_name = str(argument)
  2069. if file_name == "":
  2070. self.inform.emit(_("Open Gerber file failed."))
  2071. else:
  2072. self.on_fileopengerber(name=file_name)
  2073. return
  2074. def set_ui_title(self, name):
  2075. """
  2076. Sets the title of the main window.
  2077. :param name: String that store the project path and project name
  2078. :return: None
  2079. """
  2080. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2081. (self.version,
  2082. ('BETA' if self.beta else ''),
  2083. platform.architecture()[0],
  2084. name)
  2085. )
  2086. def defaults_read_form(self):
  2087. """
  2088. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2089. :return: None
  2090. """
  2091. for option in self.defaults_form_fields:
  2092. try:
  2093. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2094. except Exception as e:
  2095. log.debug("App.defaults_read_form() --> %s" % str(e))
  2096. def defaults_write_form(self, factor=None, fl_units=None):
  2097. """
  2098. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2099. self.defaults dictionary.
  2100. :param factor: will apply a factor to the values that written in the GUI elements
  2101. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2102. :return: None
  2103. """
  2104. for option in self.defaults:
  2105. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2106. # try:
  2107. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2108. # except KeyError:
  2109. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2110. # # TODO: Rethink this?
  2111. # pass
  2112. def defaults_write_form_field(self, field, factor=None, units=None):
  2113. """
  2114. Basically it is the worker in the self.defaults_write_form()
  2115. :param field: the GUI element in Preferences GUI to be updated
  2116. :param factor: factor to be applied to the field parameter
  2117. :param units: current FLatCAM measuring units
  2118. :return: None, it updates GUI elements
  2119. """
  2120. try:
  2121. if factor is None:
  2122. if units is None:
  2123. self.defaults_form_fields[field].set_value(self.defaults[field])
  2124. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2125. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2126. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2127. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2128. else:
  2129. if units is None:
  2130. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2131. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2132. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2133. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2134. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2135. except KeyError:
  2136. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2137. # TODO: Rethink this?
  2138. pass
  2139. except AttributeError:
  2140. log.debug(field)
  2141. def clear_pool(self):
  2142. """
  2143. Clear the multiprocessing pool and calls garbage collector.
  2144. :return: None
  2145. """
  2146. self.pool.close()
  2147. self.pool = Pool()
  2148. self.pool_recreated.emit(self.pool)
  2149. gc.collect()
  2150. def install_tools(self):
  2151. """
  2152. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2153. Instantiation of the Tools classes.
  2154. The order that the tools are installed is important as they can depend on each other install position.
  2155. :return: None
  2156. """
  2157. self.dblsidedtool = DblSidedTool(self)
  2158. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2159. self.measurement_tool = Measurement(self)
  2160. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2161. self.panelize_tool = Panelize(self)
  2162. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2163. self.film_tool = Film(self)
  2164. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2165. self.paste_tool = SolderPaste(self)
  2166. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2167. self.calculator_tool = ToolCalculator(self)
  2168. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2169. self.sub_tool = ToolSub(self)
  2170. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2171. self.move_tool = ToolMove(self)
  2172. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2173. before=self.ui.menueditorigin)
  2174. self.cutout_tool = CutOut(self)
  2175. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2176. before=self.measurement_tool.menuAction)
  2177. self.ncclear_tool = NonCopperClear(self)
  2178. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2179. before=self.measurement_tool.menuAction, separator=True)
  2180. self.paint_tool = ToolPaint(self)
  2181. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2182. before=self.measurement_tool.menuAction, separator=True)
  2183. self.transform_tool = ToolTransform(self)
  2184. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2185. self.properties_tool = Properties(self)
  2186. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2187. self.pdf_tool = ToolPDF(self)
  2188. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2189. separator=True)
  2190. self.image_tool = ToolImage(self)
  2191. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2192. separator=True)
  2193. self.pcb_wizard_tool = PcbWizard(self)
  2194. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2195. self.log.debug("Tools are installed.")
  2196. def remove_tools(self):
  2197. """
  2198. Will remove all the actions in the Tool menu.
  2199. :return: None
  2200. """
  2201. for act in self.ui.menutool.actions():
  2202. self.ui.menutool.removeAction(act)
  2203. def init_tools(self):
  2204. """
  2205. Initialize the Tool tab in the notebook side of the central widget.
  2206. Remove the actions in the Tools menu.
  2207. Instantiate again the FlatCAM tools (plugins).
  2208. All this is required when changing the layout: standard, compact etc.
  2209. :return: None
  2210. """
  2211. log.debug("init_tools()")
  2212. # delete the data currently in the Tools Tab and the Tab itself
  2213. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2214. if widget is not None:
  2215. widget.deleteLater()
  2216. self.ui.notebook.removeTab(2)
  2217. # rebuild the Tools Tab
  2218. self.ui.tool_tab = QtWidgets.QWidget()
  2219. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2220. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2221. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2222. self.ui.tool_scroll_area = VerticalScrollArea()
  2223. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2224. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2225. # first remove all of them
  2226. self.remove_tools()
  2227. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2228. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2229. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2230. # third install all of them
  2231. self.install_tools()
  2232. self.log.debug("Tools are initialized.")
  2233. # def parse_system_fonts(self):
  2234. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2235. # 'params': []})
  2236. def connect_toolbar_signals(self):
  2237. """
  2238. Reconnect the signals to the actions in the toolbar.
  2239. This has to be done each time after the FlatCAM tools are removed/installed.
  2240. :return: None
  2241. """
  2242. # Toolbar
  2243. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2244. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2245. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2246. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2247. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2248. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2249. self.ui.replot_btn.triggered.connect(self.plot_all)
  2250. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2251. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2252. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2253. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2254. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2255. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2256. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2257. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2258. self.ui.delete_btn.triggered.connect(self.on_delete)
  2259. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2260. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2261. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2262. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2263. # Tools Toolbar Signals
  2264. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2265. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2266. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2267. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2268. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2269. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2270. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2271. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2272. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2273. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2274. def object2editor(self):
  2275. """
  2276. Send the current Geometry or Excellon object (if any) into the it's editor.
  2277. :return: None
  2278. """
  2279. self.report_usage("object2editor()")
  2280. edited_object = self.collection.get_active()
  2281. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2282. isinstance(edited_object, FlatCAMExcellon):
  2283. pass
  2284. else:
  2285. self.inform.emit('[WARNING_NOTCL] %s' %
  2286. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2287. return
  2288. if isinstance(edited_object, FlatCAMGeometry):
  2289. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2290. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2291. # we set the notebook to hidden
  2292. self.ui.splitter.setSizes([0, 1])
  2293. if edited_object.multigeo is True:
  2294. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2295. if len(edited_tools) > 1:
  2296. self.inform.emit('[WARNING_NOTCL] %s' %
  2297. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2298. "is not possible.\n"
  2299. "Edit only one geometry at a time."))
  2300. # determine the tool dia of the selected tool
  2301. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2302. # now find the key in the edited_object.tools that has this tooldia
  2303. multi_tool = 1
  2304. for tool in edited_object.tools:
  2305. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2306. multi_tool = tool
  2307. break
  2308. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2309. else:
  2310. self.geo_editor.edit_fcgeometry(edited_object)
  2311. # set call source to the Editor we go into
  2312. self.call_source = 'geo_editor'
  2313. elif isinstance(edited_object, FlatCAMExcellon):
  2314. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2315. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2316. if self.ui.splitter.sizes()[0] == 0:
  2317. self.ui.splitter.setSizes([1, 1])
  2318. self.exc_editor.edit_fcexcellon(edited_object)
  2319. # set call source to the Editor we go into
  2320. self.call_source = 'exc_editor'
  2321. elif isinstance(edited_object, FlatCAMGerber):
  2322. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2323. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2324. if self.ui.splitter.sizes()[0] == 0:
  2325. self.ui.splitter.setSizes([1, 1])
  2326. self.grb_editor.edit_fcgerber(edited_object)
  2327. # set call source to the Editor we go into
  2328. self.call_source = 'grb_editor'
  2329. # make sure that we can't select another object while in Editor Mode:
  2330. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2331. self.ui.project_frame.setDisabled(True)
  2332. # delete any selection shape that might be active as they are not relevant in Editor
  2333. self.delete_selection_shape()
  2334. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2335. self.ui.plot_tab_area.protectTab(0)
  2336. self.inform.emit('[WARNING_NOTCL] %s' %
  2337. _("Editor is activated ..."))
  2338. self.should_we_save = True
  2339. def editor2object(self, cleanup=None):
  2340. """
  2341. Transfers the Geometry or Excellon from it's editor to the current object.
  2342. :return: None
  2343. """
  2344. self.report_usage("editor2object()")
  2345. # do not update a geometry or excellon object unless it comes out of an editor
  2346. if self.call_source != 'app':
  2347. edited_obj = self.collection.get_active()
  2348. if cleanup is None:
  2349. msgbox = QtWidgets.QMessageBox()
  2350. msgbox.setText(_("Do you want to save the edited object?"))
  2351. msgbox.setWindowTitle(_("Close Editor"))
  2352. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2353. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2354. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2355. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2356. msgbox.setDefaultButton(bt_yes)
  2357. msgbox.exec_()
  2358. response = msgbox.clickedButton()
  2359. if response == bt_yes:
  2360. # clean the Tools Tab
  2361. self.ui.tool_scroll_area.takeWidget()
  2362. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2363. self.ui.notebook.setTabText(2, "Tool")
  2364. if isinstance(edited_obj, FlatCAMGeometry):
  2365. obj_type = "Geometry"
  2366. if cleanup is None:
  2367. self.geo_editor.update_fcgeometry(edited_obj)
  2368. self.geo_editor.update_options(edited_obj)
  2369. self.geo_editor.deactivate()
  2370. # update the geo object options so it is including the bounding box values
  2371. try:
  2372. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2373. edited_obj.options['xmin'] = xmin
  2374. edited_obj.options['ymin'] = ymin
  2375. edited_obj.options['xmax'] = xmax
  2376. edited_obj.options['ymax'] = ymax
  2377. except AttributeError as e:
  2378. self.inform.emit('[WARNING] %s' %
  2379. _("Object empty after edit."))
  2380. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2381. elif isinstance(edited_obj, FlatCAMGerber):
  2382. obj_type = "Gerber"
  2383. if cleanup is None:
  2384. self.grb_editor.update_fcgerber()
  2385. self.grb_editor.update_options(edited_obj)
  2386. self.grb_editor.deactivate_grb_editor()
  2387. # delete the old object (the source object) if it was an empty one
  2388. if len(edited_obj.solid_geometry) == 0:
  2389. old_name = edited_obj.options['name']
  2390. self.collection.set_active(old_name)
  2391. self.collection.delete_active()
  2392. elif isinstance(edited_obj, FlatCAMExcellon):
  2393. obj_type = "Excellon"
  2394. if cleanup is None:
  2395. self.exc_editor.update_fcexcellon(edited_obj)
  2396. self.exc_editor.update_options(edited_obj)
  2397. self.exc_editor.deactivate()
  2398. else:
  2399. self.inform.emit('[WARNING_NOTCL] %s' %
  2400. _("Select a Gerber, Geometry or Excellon Object to update."))
  2401. return
  2402. self.inform.emit('[selected] %s %s' %
  2403. (obj_type, _("is updated, returning to App...")))
  2404. elif response == bt_no:
  2405. # clean the Tools Tab
  2406. self.ui.tool_scroll_area.takeWidget()
  2407. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2408. self.ui.notebook.setTabText(2, "Tool")
  2409. if isinstance(edited_obj, FlatCAMGeometry):
  2410. self.geo_editor.deactivate()
  2411. elif isinstance(edited_obj, FlatCAMGerber):
  2412. self.grb_editor.deactivate_grb_editor()
  2413. elif isinstance(edited_obj, FlatCAMExcellon):
  2414. self.exc_editor.deactivate()
  2415. # set focus on the project tab
  2416. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2417. else:
  2418. self.inform.emit('[WARNING_NOTCL] %s' %
  2419. _("Select a Gerber, Geometry or Excellon Object to update."))
  2420. return
  2421. elif response == bt_cancel:
  2422. return
  2423. else:
  2424. if isinstance(edited_obj, FlatCAMGeometry):
  2425. self.geo_editor.deactivate()
  2426. elif isinstance(edited_obj, FlatCAMGerber):
  2427. self.grb_editor.deactivate_grb_editor()
  2428. elif isinstance(edited_obj, FlatCAMExcellon):
  2429. self.exc_editor.deactivate()
  2430. else:
  2431. self.inform.emit('[WARNING_NOTCL] %s' %
  2432. _("Select a Gerber, Geometry or Excellon Object to update."))
  2433. return
  2434. # if notebook is hidden we show it
  2435. if self.ui.splitter.sizes()[0] == 0:
  2436. self.ui.splitter.setSizes([1, 1])
  2437. # restore the call_source to app
  2438. self.call_source = 'app'
  2439. edited_obj.plot()
  2440. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2441. self.ui.plot_tab_area.protectTab(0)
  2442. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2443. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2444. self.ui.project_frame.setDisabled(False)
  2445. def get_last_folder(self):
  2446. """
  2447. Get the folder path from where the last file was opened.
  2448. :return: String, last opened folder path
  2449. """
  2450. return self.defaults["global_last_folder"]
  2451. def get_last_save_folder(self):
  2452. """
  2453. Get the folder path from where the last file was saved.
  2454. :return: String, last saved folder path
  2455. """
  2456. loc = self.defaults["global_last_save_folder"]
  2457. if loc is None:
  2458. loc = self.defaults["global_last_folder"]
  2459. if loc is None:
  2460. loc = os.path.dirname(__file__)
  2461. return loc
  2462. def report_usage(self, resource):
  2463. """
  2464. Increments usage counter for the given resource
  2465. in self.defaults['global_stats'].
  2466. :param resource: Name of the resource.
  2467. :return: None
  2468. """
  2469. if resource in self.defaults['global_stats']:
  2470. self.defaults['global_stats'][resource] += 1
  2471. else:
  2472. self.defaults['global_stats'][resource] = 1
  2473. def init_tcl(self):
  2474. """
  2475. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2476. :return: None
  2477. """
  2478. if hasattr(self, 'tcl'):
  2479. # self.tcl = None
  2480. # TODO we need to clean non default variables and procedures here
  2481. # new object cannot be used here as it will not remember values created for next passes,
  2482. # because tcl was execudted in old instance of TCL
  2483. pass
  2484. else:
  2485. self.tcl = tk.Tcl()
  2486. self.setup_shell()
  2487. self.log.debug("TCL Shell has been initialized.")
  2488. # TODO: This shouldn't be here.
  2489. class TclErrorException(Exception):
  2490. """
  2491. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2492. """
  2493. pass
  2494. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2495. """
  2496. Shows a message on the FlatCAM Shell
  2497. :param msg: Message to display.
  2498. :param show: Opens the shell.
  2499. :param error: Shows the message as an error.
  2500. :param warning: Shows the message as an warning.
  2501. :param success: Shows the message as an success.
  2502. :param selected: Indicate that something was selected on canvas
  2503. :return: None
  2504. """
  2505. if show:
  2506. self.ui.shell_dock.show()
  2507. try:
  2508. if error:
  2509. self.shell.append_error(msg + "\n")
  2510. elif warning:
  2511. self.shell.append_warning(msg + "\n")
  2512. elif success:
  2513. self.shell.append_success(msg + "\n")
  2514. elif selected:
  2515. self.shell.append_selected(msg + "\n")
  2516. else:
  2517. self.shell.append_output(msg + "\n")
  2518. except AttributeError:
  2519. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2520. def raise_tcl_unknown_error(self, unknownException):
  2521. """
  2522. Raise exception if is different type than TclErrorException
  2523. this is here mainly to show unknown errors inside TCL shell console.
  2524. :param unknownException:
  2525. :return:
  2526. """
  2527. if not isinstance(unknownException, self.TclErrorException):
  2528. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2529. else:
  2530. raise unknownException
  2531. def display_tcl_error(self, error, error_info=None):
  2532. """
  2533. Escape bracket [ with '\' otherwise there is error
  2534. "ERROR: missing close-bracket" instead of real error
  2535. :param error: it may be text or exception
  2536. :param error_info: Some informations about the error
  2537. :return: None
  2538. """
  2539. if isinstance(error, Exception):
  2540. exc_type, exc_value, exc_traceback = error_info
  2541. if not isinstance(error, self.TclErrorException):
  2542. show_trace = 1
  2543. else:
  2544. show_trace = int(self.defaults['global_verbose_error_level'])
  2545. if show_trace > 0:
  2546. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2547. trc_formated = []
  2548. for a in reversed(trc):
  2549. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2550. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2551. else:
  2552. text = "%s" % error
  2553. else:
  2554. text = error
  2555. text = text.replace('[', '\\[').replace('"', '\\"')
  2556. self.tcl.eval('return -code error "%s"' % text)
  2557. def raise_tcl_error(self, text):
  2558. """
  2559. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2560. :param text: text of error
  2561. :return: raise exception
  2562. """
  2563. self.display_tcl_error(text)
  2564. raise self.TclErrorException(text)
  2565. def exec_command(self, text, no_plot=None):
  2566. """
  2567. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2568. Also handles execution in separated threads
  2569. :param text: FlatCAM TclCommand with parameters
  2570. :return: output if there was any
  2571. """
  2572. self.report_usage('exec_command')
  2573. result = self.exec_command_test(text, False)
  2574. # MS: added this method call so the geometry is updated once the TCL command is executed
  2575. if no_plot is None:
  2576. self.plot_all()
  2577. return result
  2578. def exec_command_test(self, text, reraise=True):
  2579. """
  2580. Same as exec_command(...) with additional control over exceptions.
  2581. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2582. :param text: Input command
  2583. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2584. :return: Output from the command
  2585. """
  2586. tcl_command_string = str(text)
  2587. try:
  2588. self.shell.open_proccessing() # Disables input box.
  2589. result = self.tcl.eval(str(tcl_command_string))
  2590. if result != 'None':
  2591. self.shell.append_output(result + '\n')
  2592. except tk.TclError as e:
  2593. # This will display more precise answer if something in TCL shell fails
  2594. result = self.tcl.eval("set errorInfo")
  2595. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2596. self.shell.append_error('ERROR: ' + result + '\n')
  2597. # Show error in console and just return or in test raise exception
  2598. if reraise:
  2599. raise e
  2600. finally:
  2601. self.shell.close_proccessing()
  2602. pass
  2603. return result
  2604. # """
  2605. # Code below is unsused. Saved for later.
  2606. # """
  2607. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2608. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2609. # self.log.debug(parts)
  2610. # try:
  2611. # if parts[0] not in commands:
  2612. # self.shell.append_error("Unknown command\n")
  2613. # return
  2614. #
  2615. # #import inspect
  2616. # #inspect.getargspec(someMethod)
  2617. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2618. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2619. # self.shell.append_error(
  2620. # "Command %s takes %d arguments. %d given.\n" %
  2621. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2622. # )
  2623. # return
  2624. #
  2625. # cmdfcn = commands[parts[0]]["fcn"]
  2626. # cmdconv = commands[parts[0]]["converters"]
  2627. # if len(parts) - 1 > 0:
  2628. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2629. # else:
  2630. # retval = cmdfcn()
  2631. # retfcn = commands[parts[0]]["retfcn"]
  2632. # if retval and retfcn(retval):
  2633. # self.shell.append_output(retfcn(retval) + "\n")
  2634. #
  2635. # except Exception as e:
  2636. # #self.shell.append_error(''.join(traceback.format_exc()))
  2637. # #self.shell.append_error("?\n")
  2638. # self.shell.append_error(str(e) + "\n")
  2639. def info(self, msg):
  2640. """
  2641. Informs the user. Normally on the status bar, optionally
  2642. also on the shell.
  2643. :param msg: Text to write.
  2644. :return: None
  2645. """
  2646. # Type of message in brackets at the beginning of the message.
  2647. match = re.search("\[([^\]]+)\](.*)", msg)
  2648. if match:
  2649. level = match.group(1)
  2650. msg_ = match.group(2)
  2651. self.ui.fcinfo.set_status(str(msg_), level=level)
  2652. if level.lower() == "error":
  2653. self.shell_message(msg, error=True, show=True)
  2654. elif level.lower() == "warning":
  2655. self.shell_message(msg, warning=True, show=True)
  2656. elif level.lower() == "error_notcl":
  2657. self.shell_message(msg, error=True, show=False)
  2658. elif level.lower() == "warning_notcl":
  2659. self.shell_message(msg, warning=True, show=False)
  2660. elif level.lower() == "success":
  2661. self.shell_message(msg, success=True, show=False)
  2662. elif level.lower() == "selected":
  2663. self.shell_message(msg, selected=True, show=False)
  2664. else:
  2665. self.shell_message(msg, show=False)
  2666. else:
  2667. self.ui.fcinfo.set_status(str(msg), level="info")
  2668. # make sure that if the message is to clear the infobar with a space
  2669. # is not printed over and over on the shell
  2670. if msg != '':
  2671. self.shell_message(msg)
  2672. def restore_toolbar_view(self):
  2673. """
  2674. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2675. was saved in the defaults dictionary.
  2676. :return: None
  2677. """
  2678. tb = self.defaults["global_toolbar_view"]
  2679. if tb & 1:
  2680. self.ui.toolbarfile.setVisible(True)
  2681. else:
  2682. self.ui.toolbarfile.setVisible(False)
  2683. if tb & 2:
  2684. self.ui.toolbargeo.setVisible(True)
  2685. else:
  2686. self.ui.toolbargeo.setVisible(False)
  2687. if tb & 4:
  2688. self.ui.toolbarview.setVisible(True)
  2689. else:
  2690. self.ui.toolbarview.setVisible(False)
  2691. if tb & 8:
  2692. self.ui.toolbartools.setVisible(True)
  2693. else:
  2694. self.ui.toolbartools.setVisible(False)
  2695. if tb & 16:
  2696. self.ui.exc_edit_toolbar.setVisible(True)
  2697. else:
  2698. self.ui.exc_edit_toolbar.setVisible(False)
  2699. if tb & 32:
  2700. self.ui.geo_edit_toolbar.setVisible(True)
  2701. else:
  2702. self.ui.geo_edit_toolbar.setVisible(False)
  2703. if tb & 64:
  2704. self.ui.grb_edit_toolbar.setVisible(True)
  2705. else:
  2706. self.ui.grb_edit_toolbar.setVisible(False)
  2707. if tb & 128:
  2708. self.ui.snap_toolbar.setVisible(True)
  2709. else:
  2710. self.ui.snap_toolbar.setVisible(False)
  2711. if tb & 256:
  2712. self.ui.toolbarshell.setVisible(True)
  2713. else:
  2714. self.ui.toolbarshell.setVisible(False)
  2715. def load_defaults(self, filename):
  2716. """
  2717. Loads the aplication's default settings from current_defaults.FlatConfig into
  2718. ``self.defaults``.
  2719. :return: None
  2720. """
  2721. try:
  2722. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2723. options = f.read()
  2724. f.close()
  2725. except IOError:
  2726. self.log.error("Could not load defaults file.")
  2727. self.inform.emit('[ERROR] %s' %
  2728. _("Could not load defaults file."))
  2729. # in case the defaults file can't be loaded, show all toolbars
  2730. self.defaults["global_toolbar_view"] = 511
  2731. return
  2732. try:
  2733. defaults = json.loads(options)
  2734. except:
  2735. # in case the defaults file can't be loaded, show all toolbars
  2736. self.defaults["global_toolbar_view"] = 511
  2737. e = sys.exc_info()[0]
  2738. App.log.error(str(e))
  2739. self.inform.emit('[ERROR] %s' %
  2740. _("Failed to parse defaults file."))
  2741. return
  2742. self.defaults.update(defaults)
  2743. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2744. # restore the toolbar view
  2745. self.restore_toolbar_view()
  2746. def on_import_preferences(self):
  2747. """
  2748. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2749. ``self.defaults``.
  2750. :return: None
  2751. """
  2752. self.report_usage("on_import_preferences")
  2753. App.log.debug("on_import_preferences()")
  2754. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2755. try:
  2756. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2757. directory=self.data_path,
  2758. filter=filter_)
  2759. except TypeError:
  2760. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2761. filter=filter_)
  2762. filename = str(filename)
  2763. if filename == "":
  2764. self.inform.emit('[WARNING_NOTCL] %s' %
  2765. _("FlatCAM preferences import cancelled."))
  2766. else:
  2767. try:
  2768. f = open(filename)
  2769. options = f.read()
  2770. f.close()
  2771. except IOError:
  2772. self.log.error("Could not load defaults file.")
  2773. self.inform.emit('[ERROR_NOTCL] %s' %
  2774. _("Could not load defaults file."))
  2775. return
  2776. try:
  2777. defaults_from_file = json.loads(options)
  2778. except Exception as e:
  2779. e = sys.exc_info()[0]
  2780. App.log.error(str(e))
  2781. self.inform.emit('[ERROR_NOTCL] %s' %
  2782. _("Failed to parse defaults file."))
  2783. return
  2784. self.defaults.update(defaults_from_file)
  2785. self.on_preferences_edited()
  2786. self.inform.emit('[success] %s: %s' %
  2787. (_("Imported Defaults from"), filename))
  2788. def on_export_preferences(self):
  2789. """
  2790. Save the defaults dictionary to a file.
  2791. :return: None
  2792. """
  2793. self.report_usage("on_export_preferences")
  2794. App.log.debug("on_export_preferences()")
  2795. defaults_file_content = None
  2796. self.date = str(datetime.today()).rpartition('.')[0]
  2797. self.date = ''.join(c for c in self.date if c not in ':-')
  2798. self.date = self.date.replace(' ', '_')
  2799. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2800. try:
  2801. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2802. caption=_("Export FlatCAM Preferences"),
  2803. directory=self.data_path + '/preferences_' + self.date,
  2804. filter=filter__
  2805. )
  2806. except TypeError:
  2807. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2808. filter=filter__)
  2809. filename = str(filename)
  2810. defaults_from_file = {}
  2811. if filename == "":
  2812. self.inform.emit('[WARNING_NOTCL] %s' %
  2813. _("FlatCAM preferences export cancelled."))
  2814. return
  2815. else:
  2816. try:
  2817. f = open(filename, 'w')
  2818. defaults_file_content = f.read()
  2819. f.close()
  2820. except PermissionError:
  2821. self.inform.emit('[WARNING] %s' %
  2822. _("Permission denied, saving not possible.\n"
  2823. "Most likely another app is holding the file open and not accessible."))
  2824. return
  2825. except IOError:
  2826. App.log.debug('Creating a new preferences file ...')
  2827. f = open(filename, 'w')
  2828. json.dump({}, f)
  2829. f.close()
  2830. except:
  2831. e = sys.exc_info()[0]
  2832. App.log.error("Could not load defaults file.")
  2833. App.log.error(str(e))
  2834. self.inform.emit('[ERROR_NOTCL] %s' %
  2835. _("Could not load preferences file."))
  2836. return
  2837. try:
  2838. defaults_from_file = json.loads(defaults_file_content)
  2839. except:
  2840. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2841. # Update options
  2842. self.defaults_read_form()
  2843. defaults_from_file.update(self.defaults)
  2844. self.propagate_defaults(silent=True)
  2845. # Save update options
  2846. try:
  2847. f = open(filename, "w")
  2848. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2849. f.close()
  2850. except:
  2851. self.inform.emit('[ERROR_NOTCL] %s' %
  2852. _("Failed to write defaults to file."))
  2853. return
  2854. if self.defaults["global_open_style"] is False:
  2855. self.file_opened.emit("preferences", filename)
  2856. self.file_saved.emit("preferences", filename)
  2857. self.inform.emit('[success] %s: %s' %
  2858. (_("Exported preferences to"), filename))
  2859. def on_preferences_open_folder(self):
  2860. """
  2861. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2862. :return: None
  2863. """
  2864. self.report_usage("on_preferences_open_folder()")
  2865. if sys.platform == 'win32':
  2866. subprocess.Popen('explorer %s' % self.data_path)
  2867. elif sys.platform == 'darwin':
  2868. os.system('open "%s"' % self.data_path)
  2869. else:
  2870. subprocess.Popen(['xdg-open', self.data_path])
  2871. self.inform.emit('[success] %s' %
  2872. _("FlatCAM Preferences Folder opened."))
  2873. def save_geometry(self, x, y, width, height, notebook_width):
  2874. """
  2875. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2876. launch of the application.
  2877. :param x: X position of the main window
  2878. :param y: Y position of the main window
  2879. :param width: width of the main window
  2880. :param height: height of the main window
  2881. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2882. :return: None
  2883. """
  2884. self.defaults["global_def_win_x"] = x
  2885. self.defaults["global_def_win_y"] = y
  2886. self.defaults["global_def_win_w"] = width
  2887. self.defaults["global_def_win_h"] = height
  2888. self.defaults["global_def_notebook_width"] = notebook_width
  2889. self.save_defaults()
  2890. def message_dialog(self, title, message, kind="info"):
  2891. """
  2892. Builds and show a custom QMessageBox to be used in FlatCAM.
  2893. :param title: title of the QMessageBox
  2894. :param message: message to be displayed
  2895. :param kind: type of QMessageBox; will display a specific icon.
  2896. :return:
  2897. """
  2898. icon = {"info": QtWidgets.QMessageBox.Information,
  2899. "warning": QtWidgets.QMessageBox.Warning,
  2900. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2901. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2902. dlg.setText(message)
  2903. dlg.exec_()
  2904. def register_recent(self, kind, filename):
  2905. """
  2906. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2907. dictionary.
  2908. :param kind: type of file that was opened
  2909. :param filename: the path and file name for the file that was opened
  2910. :return:
  2911. """
  2912. self.log.debug("register_recent()")
  2913. self.log.debug(" %s" % kind)
  2914. self.log.debug(" %s" % filename)
  2915. record = {'kind': str(kind), 'filename': str(filename)}
  2916. if record in self.recent:
  2917. return
  2918. if record in self.recent_projects:
  2919. return
  2920. if record['kind'] == 'project':
  2921. self.recent_projects.insert(0, record)
  2922. else:
  2923. self.recent.insert(0, record)
  2924. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2925. self.recent.pop()
  2926. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2927. self.recent_projects.pop()
  2928. try:
  2929. f = open(self.data_path + '/recent.json', 'w')
  2930. except IOError:
  2931. App.log.error("Failed to open recent items file for writing.")
  2932. self.inform.emit('[ERROR_NOTCL] %s' %
  2933. _('Failed to open recent files file for writing.'))
  2934. return
  2935. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2936. f.close()
  2937. try:
  2938. fp = open(self.data_path + '/recent_projects.json', 'w')
  2939. except IOError:
  2940. App.log.error("Failed to open recent items file for writing.")
  2941. self.inform.emit('[ERROR_NOTCL] %s' %
  2942. _('Failed to open recent projects file for writing.'))
  2943. return
  2944. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2945. fp.close()
  2946. # Re-build the recent items menu
  2947. self.setup_recent_items()
  2948. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2949. """
  2950. Creates a new specialized FlatCAMObj and attaches it to the application,
  2951. this is, updates the GUI accordingly, any other records and plots it.
  2952. This method is thread-safe.
  2953. Notes:
  2954. * If the name is in use, the self.collection will modify it
  2955. when appending it to the collection. There is no need to handle
  2956. name conflicts here.
  2957. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2958. :type kind: str
  2959. :param name: Name for the object.
  2960. :type name: str
  2961. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2962. The function is called with 2 parameters: the new object and the App instance.
  2963. :type initialize: function
  2964. :param active:
  2965. :param fit:
  2966. :param plot: If to plot the resulting object
  2967. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2968. self.colleaction
  2969. :return: None
  2970. :rtype: None
  2971. """
  2972. App.log.debug("new_object()")
  2973. obj_plot = plot
  2974. obj_autoselected = autoselected
  2975. t0 = time.time() # Debug
  2976. # ## Create object
  2977. classdict = {
  2978. "gerber": FlatCAMGerber,
  2979. "excellon": FlatCAMExcellon,
  2980. "cncjob": FlatCAMCNCjob,
  2981. "geometry": FlatCAMGeometry
  2982. }
  2983. App.log.debug("Calling object constructor...")
  2984. obj = classdict[kind](name)
  2985. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2986. # Set options from "Project options" form
  2987. self.options_read_form()
  2988. # IMPORTANT
  2989. # The key names in defaults and options dictionary's are not random:
  2990. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2991. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2992. # the options from project options form into the self.options. After that, below, depending on the type of
  2993. # object that is created, it will strip the name of the object and the underline (if the original key was
  2994. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2995. # "toolchange"
  2996. for option in self.options:
  2997. if option.find(kind + "_") == 0:
  2998. oname = option[len(kind) + 1:]
  2999. obj.options[oname] = self.options[option]
  3000. obj.isHovering = False
  3001. obj.notHovering = True
  3002. # Initialize as per user request
  3003. # User must take care to implement initialize
  3004. # in a thread-safe way as is is likely that we
  3005. # have been invoked in a separate thread.
  3006. t1 = time.time()
  3007. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3008. try:
  3009. return_value = initialize(obj, self)
  3010. except Exception as e:
  3011. msg = '[ERROR_NOTCL] %s' % \
  3012. _("An internal error has ocurred. See shell.\n")
  3013. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3014. msg += traceback.format_exc()
  3015. self.inform.emit(msg)
  3016. # if str(e) == "Empty Geometry":
  3017. # self.inform.emit("[ERROR_NOTCL] )
  3018. # else:
  3019. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3020. return "fail"
  3021. t2 = time.time()
  3022. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3023. if return_value == 'fail':
  3024. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3025. return "fail"
  3026. # Check units and convert if necessary
  3027. # This condition CAN be true because initialize() can change obj.units
  3028. if self.options["units"].upper() != obj.units.upper():
  3029. self.inform.emit('%s: %s' %
  3030. (_("Converting units to "), self.options["units"]))
  3031. obj.convert_units(self.options["units"])
  3032. t3 = time.time()
  3033. self.log.debug("%f seconds converting units." % (t3 - t2))
  3034. # Create the bounding box for the object and then add the results to the obj.options
  3035. try:
  3036. xmin, ymin, xmax, ymax = obj.bounds()
  3037. obj.options['xmin'] = xmin
  3038. obj.options['ymin'] = ymin
  3039. obj.options['xmax'] = xmax
  3040. obj.options['ymax'] = ymax
  3041. except Exception as e:
  3042. log.warning("The object has no bounds properties. %s" % str(e))
  3043. return "fail"
  3044. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3045. # Move the object to the main thread and let the app know that it is available.
  3046. obj.moveToThread(self.main_thread)
  3047. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3048. return obj
  3049. def new_excellon_object(self):
  3050. """
  3051. Creates a new, blank Excellon object.
  3052. :return: None
  3053. """
  3054. self.report_usage("new_excellon_object()")
  3055. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3056. def new_geometry_object(self):
  3057. """
  3058. Creates a new, blank and single-tool Geometry object.
  3059. :return: None
  3060. """
  3061. self.report_usage("new_geometry_object()")
  3062. def initialize(obj, self):
  3063. obj.multitool = False
  3064. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3065. def new_gerber_object(self):
  3066. """
  3067. Creates a new, blank Gerber object.
  3068. :return: None
  3069. """
  3070. self.report_usage("new_gerber_object()")
  3071. def initialize(grb_obj, self):
  3072. grb_obj.multitool = False
  3073. grb_obj.source_file = []
  3074. grb_obj.multigeo = False
  3075. grb_obj.follow = False
  3076. grb_obj.apertures = {}
  3077. grb_obj.solid_geometry = []
  3078. try:
  3079. grb_obj.options['xmin'] = 0
  3080. grb_obj.options['ymin'] = 0
  3081. grb_obj.options['xmax'] = 0
  3082. grb_obj.options['ymax'] = 0
  3083. except KeyError:
  3084. pass
  3085. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3086. def on_object_created(self, obj, plot, autoselect):
  3087. """
  3088. Event callback for object creation.
  3089. It will add the new object to the collection. After that it will plot the object in a threaded way
  3090. :param obj: The newly created FlatCAM object.
  3091. :param plot: if the newly create object t obe plotted
  3092. :param autoselect: if the newly created object to be autoselected after creation
  3093. :return: None
  3094. """
  3095. t0 = time.time() # DEBUG
  3096. self.log.debug("on_object_created()")
  3097. # The Collection might change the name if there is a collision
  3098. self.collection.append(obj)
  3099. # after adding the object to the collection always update the list of objects that are in the collection
  3100. self.all_objects_list = self.collection.get_list()
  3101. # self.inform.emit('[selected] %s created & selected: %s' %
  3102. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3103. if obj.kind == 'gerber':
  3104. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3105. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3106. elif obj.kind == 'excellon':
  3107. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3108. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3109. elif obj.kind == 'cncjob':
  3110. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3111. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3112. elif obj.kind == 'geometry':
  3113. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3114. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3115. # update the SHELL auto-completer model with the name of the new object
  3116. self.myKeywords.append(obj.options['name'])
  3117. self.shell._edit.set_model_data(self.myKeywords)
  3118. self.ui.code_editor.set_model_data(self.myKeywords)
  3119. if autoselect:
  3120. # select the just opened object but deselect the previous ones
  3121. self.collection.set_all_inactive()
  3122. self.collection.set_active(obj.options["name"])
  3123. else:
  3124. self.collection.set_all_inactive()
  3125. # here it is done the object plotting
  3126. def worker_task(t_obj):
  3127. with self.proc_container.new(_("Plotting")):
  3128. if isinstance(t_obj, FlatCAMCNCjob):
  3129. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3130. else:
  3131. t_obj.plot()
  3132. t1 = time.time() # DEBUG
  3133. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3134. self.object_plotted.emit(t_obj)
  3135. # Send to worker
  3136. # self.worker.add_task(worker_task, [self])
  3137. if plot is True:
  3138. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3139. def on_object_changed(self, obj):
  3140. """
  3141. Called whenever the geometry of the object was changed in some way.
  3142. This require the update of it's bounding values so it can be the selected on canvas.
  3143. Update the bounding box data from obj.options
  3144. :param obj: the object that was changed
  3145. :return: None
  3146. """
  3147. xmin, ymin, xmax, ymax = obj.bounds()
  3148. obj.options['xmin'] = xmin
  3149. obj.options['ymin'] = ymin
  3150. obj.options['xmax'] = xmax
  3151. obj.options['ymax'] = ymax
  3152. log.debug("Object changed, updating the bounding box data on self.options")
  3153. # delete the old selection shape
  3154. self.delete_selection_shape()
  3155. self.should_we_save = True
  3156. def on_object_plotted(self, obj):
  3157. """
  3158. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3159. :param obj: object to be fit into view
  3160. :return: None
  3161. """
  3162. self.on_zoom_fit(None)
  3163. def options_read_form(self):
  3164. """
  3165. Same as it's equivalent from the defaults.
  3166. self.options use to store the preferences per project. No longer used.
  3167. :return: None
  3168. """
  3169. for option in self.options_form_fields:
  3170. self.options[option] = self.options_form_fields[option].get_value()
  3171. def options_write_form(self):
  3172. """
  3173. Same as it's equivalent from the defaults.
  3174. self.options use to store the preferences per project. No longer used.
  3175. :return: None
  3176. """
  3177. for option in self.options:
  3178. self.options_write_form_field(option)
  3179. def options_write_form_field(self, field):
  3180. """
  3181. Same as it's equivalent from the defaults.
  3182. self.options use to store the preferences per project. No longer used.
  3183. :return: None
  3184. """
  3185. try:
  3186. self.options_form_fields[field].set_value(self.options[field])
  3187. except KeyError:
  3188. # Changed from error to debug. This allows to have data stored
  3189. # which is not user-editable.
  3190. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3191. pass
  3192. def on_about(self):
  3193. """
  3194. Displays the "about" dialog found in the Menu --> Help.
  3195. :return: None
  3196. """
  3197. self.report_usage("on_about")
  3198. version = self.version
  3199. version_date = self.version_date
  3200. beta = self.beta
  3201. class AboutDialog(QtWidgets.QDialog):
  3202. def __init__(self, parent=None):
  3203. QtWidgets.QDialog.__init__(self, parent)
  3204. # Icon and title
  3205. self.setWindowIcon(parent.app_icon)
  3206. self.setWindowTitle(_("About FlatCAM"))
  3207. self.resize(600, 200)
  3208. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3209. # self.setStyleSheet(
  3210. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3211. # "background-attachment: fixed"
  3212. # )
  3213. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3214. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3215. # palette = QtGui.QPalette()
  3216. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3217. # self.setPalette(palette)
  3218. logo = QtWidgets.QLabel()
  3219. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3220. title = QtWidgets.QLabel(
  3221. "<font size=8><B>FlatCAM</B></font><BR>"
  3222. "{title}<BR>"
  3223. "<BR>"
  3224. "<BR>"
  3225. "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3226. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  3227. "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3228. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  3229. "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3230. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">here.</a><BR>".
  3231. format(title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3232. devel=_("Development"), down=_("DOWNLOAD"), issue=_("Issue tracker"))
  3233. )
  3234. title.setOpenExternalLinks(True)
  3235. closebtn = QtWidgets.QPushButton(_("Close"))
  3236. tab_widget = QtWidgets.QTabWidget()
  3237. description_label = QtWidgets.QLabel(
  3238. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3239. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3240. version=version,beta=('BETA' if beta else ''),
  3241. date=version_date,
  3242. arch=platform.architecture()[0])
  3243. )
  3244. description_label.setOpenExternalLinks(True)
  3245. license_label = QtWidgets.QLabel(
  3246. _(
  3247. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3248. 'Licensed under the MIT license:\n'
  3249. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3250. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3251. 'of this software and associated documentation files (the "Software"), to deal\n'
  3252. 'in the Software without restriction, including without limitation the rights\n'
  3253. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3254. 'copies of the Software, and to permit persons to whom the Software is\n'
  3255. ' furnished to do so, subject to the following conditions:\n\n'
  3256. 'The above copyright notice and this permission notice shall be included in\n'
  3257. 'all copies or substantial portions of the Software.\n\n'
  3258. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3259. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3260. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3261. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3262. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3263. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3264. 'THE SOFTWARE.'
  3265. )
  3266. )
  3267. license_label.setOpenExternalLinks(True)
  3268. # layouts
  3269. layout1 = QtWidgets.QVBoxLayout()
  3270. layout1_1 = QtWidgets.QHBoxLayout()
  3271. layout1_2 = QtWidgets.QHBoxLayout()
  3272. layout2 = QtWidgets.QHBoxLayout()
  3273. layout3 = QtWidgets.QHBoxLayout()
  3274. self.setLayout(layout1)
  3275. layout1.addLayout(layout1_1)
  3276. layout1.addLayout(layout1_2)
  3277. layout1.addLayout(layout2)
  3278. layout1.addLayout(layout3)
  3279. layout1_1.addStretch()
  3280. layout1_1.addWidget(description_label)
  3281. layout1_2.addWidget(tab_widget)
  3282. self.splash_tab = QtWidgets.QWidget()
  3283. self.splash_tab.setObjectName("splash_about")
  3284. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3285. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3286. tab_widget.addTab(self.splash_tab, _("Splash"))
  3287. self.programmmers_tab = QtWidgets.QWidget()
  3288. self.programmmers_tab.setObjectName("programmers_about")
  3289. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3290. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3291. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3292. self.translators_tab = QtWidgets.QWidget()
  3293. self.translators_tab.setObjectName("translators_about")
  3294. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3295. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3296. tab_widget.addTab(self.translators_tab, _("Translators"))
  3297. self.license_tab = QtWidgets.QWidget()
  3298. self.license_tab.setObjectName("license_about")
  3299. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3300. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3301. tab_widget.addTab(self.license_tab, _("License"))
  3302. self.splash_tab_layout.addWidget(logo, stretch=0)
  3303. self.splash_tab_layout.addWidget(title, stretch=1)
  3304. self.prog_grid_lay = QtWidgets.QGridLayout()
  3305. prog_widget = QtWidgets.QWidget()
  3306. prog_widget.setLayout(self.prog_grid_lay)
  3307. self.programmmers_tab_layout.addWidget(prog_widget)
  3308. self.programmmers_tab_layout.addStretch()
  3309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  3313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 1)
  3315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  3317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Maintainer >=2019")), 4, 1)
  3319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 5, 0)
  3320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 1)
  3321. self.translator_grid_lay = QtWidgets.QGridLayout()
  3322. trans_widget = QtWidgets.QWidget()
  3323. trans_widget.setLayout(self.translator_grid_lay)
  3324. self.translators_tab_layout.addWidget(trans_widget)
  3325. self.translators_tab_layout.addStretch()
  3326. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3327. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3328. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3329. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3330. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3331. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3332. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3333. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3334. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3335. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3336. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3337. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3338. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3339. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3344. self.translator_grid_lay.setColumnStretch(0, 0)
  3345. # self.translators_tab_layout.addStretch()
  3346. self.license_tab_layout.addWidget(license_label)
  3347. self.license_tab_layout.addStretch()
  3348. layout3.addStretch()
  3349. layout3.addWidget(closebtn)
  3350. closebtn.clicked.connect(self.accept)
  3351. AboutDialog(self.ui).exec_()
  3352. def on_file_savedefaults(self):
  3353. """
  3354. Callback for menu item File->Save Defaults. Saves application default options
  3355. ``self.defaults`` to current_defaults.FlatConfig.
  3356. :return: None
  3357. """
  3358. self.save_defaults()
  3359. # def on_app_exit(self):
  3360. # self.report_usage("on_app_exit()")
  3361. #
  3362. # if self.collection.get_list():
  3363. # msgbox = QtWidgets.QMessageBox()
  3364. # # msgbox.setText("<B>Save changes ...</B>")
  3365. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3366. # "\n"
  3367. # "Do you want to Save the project?")
  3368. # msgbox.setWindowTitle("Save changes")
  3369. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3370. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3371. # QtWidgets.QMessageBox.Cancel)
  3372. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3373. #
  3374. # response = msgbox.exec_()
  3375. #
  3376. # if response == QtWidgets.QMessageBox.Yes:
  3377. # self.on_file_saveprojectas(thread=False)
  3378. # elif response == QtWidgets.QMessageBox.Cancel:
  3379. # return
  3380. # self.save_defaults()
  3381. # else:
  3382. # self.save_defaults()
  3383. # log.debug("Application defaults saved ... Exit event.")
  3384. # QtWidgets.qApp.quit()
  3385. def save_defaults(self, silent=False, data_path=None):
  3386. """
  3387. Saves application default options
  3388. ``self.defaults`` to current_defaults.FlatConfig file.
  3389. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3390. used at the next launch of the application.
  3391. :param silent: whether to display a message in status bar or not; boolean
  3392. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3393. When the application is portable it should be a mobile location.
  3394. :return: None
  3395. """
  3396. self.report_usage("save_defaults")
  3397. if data_path is None:
  3398. data_path = self.data_path
  3399. # Read options from file
  3400. try:
  3401. f = open(data_path + "/current_defaults.FlatConfig")
  3402. defaults_file_content = f.read()
  3403. f.close()
  3404. except:
  3405. e = sys.exc_info()[0]
  3406. App.log.error("Could not load defaults file.")
  3407. App.log.error(str(e))
  3408. self.inform.emit('[ERROR_NOTCL] %s' %
  3409. _("Could not load defaults file."))
  3410. return
  3411. try:
  3412. defaults = json.loads(defaults_file_content)
  3413. except:
  3414. e = sys.exc_info()[0]
  3415. App.log.error("Failed to parse defaults file.")
  3416. App.log.error(str(e))
  3417. self.inform.emit('[ERROR_NOTCL] %s' %
  3418. _("Failed to parse defaults file."))
  3419. return
  3420. # Update options
  3421. self.defaults_read_form()
  3422. defaults.update(self.defaults)
  3423. self.propagate_defaults(silent=True)
  3424. # Save the toolbar view
  3425. tb_status = 0
  3426. if self.ui.toolbarfile.isVisible():
  3427. tb_status += 1
  3428. if self.ui.toolbargeo.isVisible():
  3429. tb_status += 2
  3430. if self.ui.toolbarview.isVisible():
  3431. tb_status += 4
  3432. if self.ui.toolbartools.isVisible():
  3433. tb_status += 8
  3434. if self.ui.exc_edit_toolbar.isVisible():
  3435. tb_status += 16
  3436. if self.ui.geo_edit_toolbar.isVisible():
  3437. tb_status += 32
  3438. if self.ui.grb_edit_toolbar.isVisible():
  3439. tb_status += 64
  3440. if self.ui.snap_toolbar.isVisible():
  3441. tb_status += 128
  3442. if self.ui.toolbarshell.isVisible():
  3443. tb_status += 256
  3444. self.defaults["global_toolbar_view"] = tb_status
  3445. # Save update options
  3446. try:
  3447. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3448. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3449. f.close()
  3450. except:
  3451. self.inform.emit('[ERROR_NOTCL] %s' %
  3452. _("Failed to write defaults to file."))
  3453. return
  3454. if not silent:
  3455. self.inform.emit('[success] %s' %
  3456. _("Preferences saved."))
  3457. def save_factory_defaults(self, silent=False, data_path=None):
  3458. """
  3459. Saves application factory default options
  3460. ``self.defaults`` to factory_defaults.FlatConfig.
  3461. It's a one time job done just after the first install.
  3462. :param silent: whether to display a message in status bar or not; boolean
  3463. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3464. When the application is portable it should be a mobile location.
  3465. :return: None
  3466. """
  3467. self.report_usage("save_factory_defaults")
  3468. if data_path is None:
  3469. data_path = self.data_path
  3470. # Read options from file
  3471. try:
  3472. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3473. factory_defaults_file_content = f_f_def.read()
  3474. f_f_def.close()
  3475. except:
  3476. e = sys.exc_info()[0]
  3477. App.log.error("Could not load factory defaults file.")
  3478. App.log.error(str(e))
  3479. self.inform.emit('[ERROR_NOTCL] %s' %
  3480. _("Could not load factory defaults file."))
  3481. return
  3482. try:
  3483. factory_defaults = json.loads(factory_defaults_file_content)
  3484. except:
  3485. e = sys.exc_info()[0]
  3486. App.log.error("Failed to parse factory defaults file.")
  3487. App.log.error(str(e))
  3488. self.inform.emit('[ERROR_NOTCL] %s' %
  3489. _("Failed to parse factory defaults file."))
  3490. return
  3491. # Update options
  3492. self.defaults_read_form()
  3493. factory_defaults.update(self.defaults)
  3494. self.propagate_defaults(silent=True)
  3495. # Save update options
  3496. try:
  3497. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3498. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3499. f_f_def_s.close()
  3500. except:
  3501. self.inform.emit('[ERROR_NOTCL] %s' %
  3502. _("Failed to write factory defaults to file."))
  3503. return
  3504. if silent is False:
  3505. self.inform.emit(_("Factory defaults saved."))
  3506. def final_save(self):
  3507. """
  3508. Callback for doing a preferences save to file whenever the application is about to quit.
  3509. If the project has changes, it will ask the user to save the project.
  3510. :return: None
  3511. """
  3512. if self.save_in_progress:
  3513. self.inform.emit('[WARNING_NOTCL] %s' %
  3514. _("Application is saving the project. Please wait ..."))
  3515. return
  3516. if self.should_we_save and self.collection.get_list():
  3517. msgbox = QtWidgets.QMessageBox()
  3518. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3519. "\n"
  3520. "Do you want to Save the project?"))
  3521. msgbox.setWindowTitle(_("Save changes"))
  3522. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3523. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3524. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3525. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3526. msgbox.setDefaultButton(bt_yes)
  3527. msgbox.exec_()
  3528. response = msgbox.clickedButton()
  3529. if response == bt_yes:
  3530. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3531. elif response == bt_no:
  3532. self.quit_application()
  3533. elif response == bt_cancel:
  3534. return
  3535. else:
  3536. self.quit_application()
  3537. def quit_application(self):
  3538. """
  3539. Called (as a pyslot or not) when the application is quit.
  3540. :return: None
  3541. """
  3542. self.save_defaults()
  3543. log.debug("App.final_save() --> App Defaults saved.")
  3544. # save toolbar state to file
  3545. settings = QSettings("Open Source", "FlatCAM")
  3546. settings.setValue('saved_gui_state', self.ui.saveState())
  3547. settings.setValue('maximized_gui', self.ui.isMaximized())
  3548. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3549. settings.setValue('notebook_font_size',
  3550. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3551. settings.setValue('axis_font_size',
  3552. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3553. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3554. # This will write the setting to the platform specific storage.
  3555. del settings
  3556. log.debug("App.final_save() --> App UI state saved.")
  3557. QtWidgets.qApp.quit()
  3558. def on_portable_checked(self, state):
  3559. """
  3560. Callback called when the checkbox in Preferences GUI is checked.
  3561. It will set the application as portable by creating the preferences and recent files in the
  3562. 'config' folder found in the FlatCAM installation folder.
  3563. :param state: boolean, the state of the checkbox when clicked/checked
  3564. :return:
  3565. """
  3566. line_no = 0
  3567. data = None
  3568. if sys.platform != 'win32':
  3569. # this won't work in Linux or MacOS
  3570. return
  3571. # test if the app was frozen and choose the path for the configuration file
  3572. if getattr(sys, "frozen", False) is True:
  3573. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3574. else:
  3575. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3576. config_file = current_data_path + '\\configuration.txt'
  3577. try:
  3578. with open(config_file, 'r') as f:
  3579. try:
  3580. data = f.readlines()
  3581. except Exception as e:
  3582. log.debug('App.__init__() -->%s' % str(e))
  3583. return
  3584. except FileNotFoundError:
  3585. pass
  3586. for line in data:
  3587. line = line.strip('\n')
  3588. param = str(line).rpartition('=')
  3589. if param[0] == 'portable':
  3590. break
  3591. line_no += 1
  3592. if state:
  3593. data[line_no] = 'portable=True\n'
  3594. # create the new defauults files
  3595. # create current_defaults.FlatConfig file if there is none
  3596. try:
  3597. f = open(current_data_path + '/current_defaults.FlatConfig')
  3598. f.close()
  3599. except IOError:
  3600. App.log.debug('Creating empty current_defaults.FlatConfig')
  3601. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3602. json.dump({}, f)
  3603. f.close()
  3604. # create factory_defaults.FlatConfig file if there is none
  3605. try:
  3606. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3607. f.close()
  3608. except IOError:
  3609. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3610. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3611. json.dump({}, f)
  3612. f.close()
  3613. try:
  3614. f = open(current_data_path + '/recent.json')
  3615. f.close()
  3616. except IOError:
  3617. App.log.debug('Creating empty recent.json')
  3618. f = open(current_data_path + '/recent.json', 'w')
  3619. json.dump([], f)
  3620. f.close()
  3621. try:
  3622. fp = open(current_data_path + '/recent_projects.json')
  3623. fp.close()
  3624. except IOError:
  3625. App.log.debug('Creating empty recent_projects.json')
  3626. fp = open(current_data_path + '/recent_projects.json', 'w')
  3627. json.dump([], fp)
  3628. fp.close()
  3629. # save the current defaults to the new defaults file
  3630. self.save_defaults(silent=True, data_path=current_data_path)
  3631. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3632. else:
  3633. data[line_no] = 'portable=False\n'
  3634. with open(config_file, 'w') as f:
  3635. f.writelines(data)
  3636. def on_toggle_shell(self):
  3637. """
  3638. Toggle shell: if is visible close it, if it is closed then open it
  3639. :return:
  3640. """
  3641. self.report_usage("on_toggle_shell()")
  3642. if self.ui.shell_dock.isVisible():
  3643. self.ui.shell_dock.hide()
  3644. else:
  3645. self.ui.shell_dock.show()
  3646. def on_register_files(self, obj_type=None):
  3647. """
  3648. Called whenever there is a need to register file extensions with FlatCAM.
  3649. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3650. :param obj_type: the type of object to be register for.
  3651. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3652. :return: None
  3653. """
  3654. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3655. new_reg_path = 'Software\\Classes\\'
  3656. # find if the current user is admin
  3657. try:
  3658. is_admin = os.getuid() == 0
  3659. except AttributeError:
  3660. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3661. if is_admin is True:
  3662. root_path = winreg.HKEY_CLASSES_ROOT
  3663. else:
  3664. root_path = winreg.HKEY_CURRENT_USER
  3665. # create the keys
  3666. def set_reg(name, root_path, new_reg_path, value):
  3667. try:
  3668. winreg.CreateKey(root_path, new_reg_path)
  3669. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3670. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3671. return True
  3672. except WindowsError:
  3673. return False
  3674. # delete key in registry
  3675. def delete_reg(root_path, reg_path, key_to_del):
  3676. key_to_del_path = reg_path + key_to_del
  3677. try:
  3678. winreg.DeleteKey(root_path, key_to_del_path)
  3679. return True
  3680. except WindowsError:
  3681. return False
  3682. if obj_type is None or obj_type == 'excellon':
  3683. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3684. exc_list = [x for x in exc_list if x != '']
  3685. # register all keys in the Preferences window
  3686. for ext in exc_list:
  3687. new_k = new_reg_path + ext
  3688. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3689. # and unregister those that are no longer in the Preferences windows but are in the file
  3690. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3691. if ext not in exc_list:
  3692. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3693. # now write the updated extensions to the self.defaults
  3694. new_ext = ''
  3695. for ext in exc_list:
  3696. new_ext = new_ext + ext + ', '
  3697. self.defaults["fa_excellon"] = new_ext
  3698. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3699. if obj_type is None or obj_type == 'gcode':
  3700. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3701. gco_list = [x for x in gco_list if x != '']
  3702. # register all keys in the Preferences window
  3703. for ext in gco_list:
  3704. new_k = new_reg_path + ext
  3705. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3706. # and unregister those that are no longer in the Preferences windows but are in the file
  3707. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3708. if ext not in gco_list:
  3709. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3710. # now write the updated extensions to the self.defaults
  3711. new_ext = ''
  3712. for ext in gco_list:
  3713. new_ext = new_ext + ext + ', '
  3714. self.defaults["fa_gcode"] = new_ext
  3715. self.inform.emit('[success] %s' %
  3716. _("Selected GCode file extensions registered with FlatCAM."))
  3717. if obj_type is None or obj_type == 'gerber':
  3718. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3719. grb_list = [x for x in grb_list if x != '']
  3720. # register all keys in the Preferences window
  3721. for ext in grb_list:
  3722. new_k = new_reg_path + ext
  3723. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3724. # and unregister those that are no longer in the Preferences windows but are in the file
  3725. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3726. if ext not in grb_list:
  3727. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3728. # now write the updated extensions to the self.defaults
  3729. new_ext = ''
  3730. for ext in grb_list:
  3731. new_ext = new_ext + ext + ', '
  3732. self.defaults["fa_gerber"] = new_ext
  3733. self.inform.emit('[success] %s' %
  3734. _("Selected Gerber file extensions registered with FlatCAM."))
  3735. def on_edit_join(self, name=None):
  3736. """
  3737. Callback for Edit->Join. Joins the selected geometry objects into
  3738. a new one.
  3739. :return: None
  3740. """
  3741. self.report_usage("on_edit_join()")
  3742. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3743. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3744. tooldias = []
  3745. geo_type_list = set()
  3746. objs = self.collection.get_selected()
  3747. if len(objs) < 2:
  3748. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3749. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3750. return 'fail'
  3751. for obj in objs:
  3752. geo_type_list.add(obj.multigeo)
  3753. # if len(geo_type_list) == 1 means that all list elements are the same
  3754. if len(geo_type_list) != 1:
  3755. self.inform.emit('[ERROR] %s' %
  3756. _("Failed join. The Geometry objects are of different types.\n"
  3757. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3758. "convert from one to another and retry joining \n"
  3759. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3760. "the result may not be what was expected. \n"
  3761. "Check the generated GCODE."))
  3762. return
  3763. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3764. if True in geo_type_list:
  3765. def initialize(obj, app):
  3766. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3767. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3768. for v in obj.tools.values():
  3769. v['data']['name'] = obj_name_multi
  3770. self.new_object("geometry", obj_name_multi, initialize)
  3771. else:
  3772. def initialize(obj, app):
  3773. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3774. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3775. for v in obj.tools.values():
  3776. v['data']['name'] = obj_name_single
  3777. self.new_object("geometry", obj_name_single, initialize)
  3778. self.should_we_save = True
  3779. def on_edit_join_exc(self):
  3780. """
  3781. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3782. a new Excellon.
  3783. :return: None
  3784. """
  3785. self.report_usage("on_edit_join_exc()")
  3786. objs = self.collection.get_selected()
  3787. for obj in objs:
  3788. if not isinstance(obj, FlatCAMExcellon):
  3789. self.inform.emit('[ERROR_NOTCL] %s' %
  3790. _("Failed. Excellon joining works only on Excellon objects."))
  3791. return
  3792. if len(objs) < 2:
  3793. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3794. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3795. return 'fail'
  3796. def initialize(obj, app):
  3797. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3798. self.new_object("excellon", 'Combo_Excellon', initialize)
  3799. self.should_we_save = True
  3800. def on_edit_join_grb(self):
  3801. """
  3802. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3803. a new Gerber object.
  3804. :return: None
  3805. """
  3806. self.report_usage("on_edit_join_grb()")
  3807. objs = self.collection.get_selected()
  3808. for obj in objs:
  3809. if not isinstance(obj, FlatCAMGerber):
  3810. self.inform.emit('[ERROR_NOTCL] %s' %
  3811. _("Failed. Gerber joining works only on Gerber objects."))
  3812. return
  3813. if len(objs) < 2:
  3814. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3815. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3816. return 'fail'
  3817. def initialize(obj, app):
  3818. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3819. self.new_object("gerber", 'Combo_Gerber', initialize)
  3820. self.should_we_save = True
  3821. def on_convert_singlegeo_to_multigeo(self):
  3822. """
  3823. Called for converting a Geometry object from single-geo to multi-geo.
  3824. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3825. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3826. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3827. the solid-geometry of that tool.
  3828. :return: None
  3829. """
  3830. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3831. obj = self.collection.get_active()
  3832. if obj is None:
  3833. self.inform.emit('[ERROR_NOTCL] %s' %
  3834. _("Failed. Select a Geometry Object and try again."))
  3835. return
  3836. if not isinstance(obj, FlatCAMGeometry):
  3837. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3838. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3839. return
  3840. obj.multigeo = True
  3841. for tooluid, dict_value in obj.tools.items():
  3842. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3843. if not isinstance(obj.solid_geometry, list):
  3844. obj.solid_geometry = [obj.solid_geometry]
  3845. obj.solid_geometry[:] = []
  3846. obj.plot()
  3847. self.should_we_save = True
  3848. self.inform.emit('[success] %s' %
  3849. _("A Geometry object was converted to MultiGeo type."))
  3850. def on_convert_multigeo_to_singlegeo(self):
  3851. """
  3852. Called for converting a Geometry object from multi-geo to single-geo.
  3853. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3854. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3855. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3856. the solid-geometry of that tool.
  3857. :return: None
  3858. """
  3859. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3860. obj = self.collection.get_active()
  3861. if obj is None:
  3862. self.inform.emit('[ERROR_NOTCL] %s' %
  3863. _("Failed. Select a Geometry Object and try again."))
  3864. return
  3865. if not isinstance(obj, FlatCAMGeometry):
  3866. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3867. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3868. return
  3869. obj.multigeo = False
  3870. total_solid_geometry = []
  3871. for tooluid, dict_value in obj.tools.items():
  3872. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3873. # clear the original geometry
  3874. dict_value['solid_geometry'][:] = []
  3875. obj.solid_geometry = deepcopy(total_solid_geometry)
  3876. obj.plot()
  3877. self.should_we_save = True
  3878. self.inform.emit('[success] %s' %
  3879. _("A Geometry object was converted to SingleGeo type."))
  3880. def on_options_dict_change(self, field):
  3881. """
  3882. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3883. current project. This feature is no longer used.
  3884. :param field:
  3885. :return:
  3886. """
  3887. self.options_write_form_field(field)
  3888. if field == "units":
  3889. self.set_screen_units(self.options['units'])
  3890. def on_defaults_dict_change(self, field):
  3891. """
  3892. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3893. Edit -> Preferences tab window.
  3894. :param field: the key of the self.defaults dictionary that was changed.
  3895. :return: None
  3896. """
  3897. self.defaults_write_form_field(field)
  3898. if field == "units":
  3899. self.set_screen_units(self.defaults['units'])
  3900. def set_screen_units(self, units):
  3901. """
  3902. Set the FlatCAM units on the status bar.
  3903. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3904. :return: None
  3905. """
  3906. self.ui.units_label.setText("[" + units.lower() + "]")
  3907. def on_toggle_units(self, no_pref=False):
  3908. """
  3909. Callback for the Units radio-button change in the Preferences tab.
  3910. Changes the application's default units adn for the project too.
  3911. If changing the project's units, the change propagates to all of
  3912. the objects in the project.
  3913. :return: None
  3914. """
  3915. self.report_usage("on_toggle_units")
  3916. if self.toggle_units_ignore:
  3917. return
  3918. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3919. # If option is the same, then ignore
  3920. if new_units == self.defaults["units"].upper():
  3921. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3922. return
  3923. # Options to scale
  3924. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3925. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3926. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3927. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3928. "excellon_z_pdepth",
  3929. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3930. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3931. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3932. "geometry_feedrate_probe",
  3933. 'cncjob_tooldia',
  3934. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3935. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  3936. "tools_2sided_drilldia", "tools_film_boundary",
  3937. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3938. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3939. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3940. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3941. "tools_transform_offset_y",
  3942. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3943. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3944. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3945. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3946. 'global_gridx', 'global_gridy', 'global_snap_max']
  3947. def scale_options(sfactor):
  3948. for dim in dimensions:
  3949. if dim == 'excellon_toolchangexy':
  3950. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3951. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3952. coords_xy[0] *= sfactor
  3953. coords_xy[1] *= sfactor
  3954. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3955. elif dim == 'geometry_toolchangexy':
  3956. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3957. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3958. coords_xy[0] *= sfactor
  3959. coords_xy[1] *= sfactor
  3960. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3961. elif dim == 'geometry_cnctooldia':
  3962. tools_diameters = []
  3963. try:
  3964. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3965. tools_diameters = [eval(a) for a in tools_string if a != '']
  3966. except Exception as e:
  3967. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3968. self.options['geometry_cnctooldia'] = ''
  3969. for t in range(len(tools_diameters)):
  3970. tools_diameters[t] *= sfactor
  3971. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3972. elif dim == 'tools_ncctools':
  3973. ncctools = []
  3974. try:
  3975. tools_string = self.defaults["tools_ncctools"].split(",")
  3976. ncctools = [eval(a) for a in tools_string if a != '']
  3977. except Exception as e:
  3978. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3979. self.options['tools_ncctools'] = ''
  3980. for t in range(len(ncctools)):
  3981. ncctools[t] *= sfactor
  3982. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3983. elif dim == 'tools_solderpaste_tools':
  3984. sptools = []
  3985. try:
  3986. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3987. sptools = [eval(a) for a in tools_string if a != '']
  3988. except Exception as e:
  3989. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3990. self.options['tools_solderpaste_tools'] = ""
  3991. for t in range(len(sptools)):
  3992. sptools[t] *= sfactor
  3993. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3994. elif dim == 'tools_solderpaste_xy_toolchange':
  3995. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3996. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3997. sp_coords[0] *= sfactor
  3998. sp_coords[1] *= sfactor
  3999. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4000. elif dim == 'global_gridx' or dim == 'global_gridy':
  4001. if new_units == 'IN':
  4002. val = 0.1
  4003. try:
  4004. val = float(self.defaults[dim]) * sfactor
  4005. except Exception as e:
  4006. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4007. self.options[dim] = float('%.6f' % val)
  4008. else:
  4009. val = 0.1
  4010. try:
  4011. val = float(self.defaults[dim]) * sfactor
  4012. except Exception as e:
  4013. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4014. self.options[dim] = float('%.4f' % val)
  4015. else:
  4016. val = 0.1
  4017. try:
  4018. val = float(self.options[dim]) * sfactor
  4019. except Exception as e:
  4020. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4021. self.options[dim] = val
  4022. def scale_defaults(sfactor):
  4023. for dim in dimensions:
  4024. if dim == 'excellon_toolchangexy':
  4025. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4026. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4027. coords_xy[0] *= sfactor
  4028. coords_xy[1] *= sfactor
  4029. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4030. elif dim == 'geometry_toolchangexy':
  4031. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4032. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4033. coords_xy[0] *= sfactor
  4034. coords_xy[1] *= sfactor
  4035. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4036. elif dim == 'geometry_cnctooldia':
  4037. tools_diameters = []
  4038. try:
  4039. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4040. tools_diameters = [eval(a) for a in tools_string if a != '']
  4041. except Exception as e:
  4042. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4043. self.defaults['geometry_cnctooldia'] = ''
  4044. for t in range(len(tools_diameters)):
  4045. tools_diameters[t] *= sfactor
  4046. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4047. elif dim == 'tools_ncctools':
  4048. ncctools = []
  4049. try:
  4050. tools_string = self.defaults["tools_ncctools"].split(",")
  4051. ncctools = [eval(a) for a in tools_string if a != '']
  4052. except Exception as e:
  4053. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4054. self.defaults['tools_ncctools'] = ''
  4055. for t in range(len(ncctools)):
  4056. ncctools[t] *= sfactor
  4057. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4058. elif dim == 'tools_solderpaste_tools':
  4059. sptools = []
  4060. try:
  4061. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4062. sptools = [eval(a) for a in tools_string if a != '']
  4063. except Exception as e:
  4064. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4065. self.defaults['tools_solderpaste_tools'] = ""
  4066. for t in range(len(sptools)):
  4067. sptools[t] *= sfactor
  4068. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4069. elif dim == 'tools_solderpaste_xy_toolchange':
  4070. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4071. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4072. sp_coords[0] *= sfactor
  4073. sp_coords[1] *= sfactor
  4074. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4075. elif dim == 'global_gridx' or dim == 'global_gridy':
  4076. if new_units == 'IN':
  4077. val = 0.1
  4078. try:
  4079. val = float(self.defaults[dim]) * sfactor
  4080. except Exception as e:
  4081. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4082. self.defaults[dim] = float('%.6f' % val)
  4083. else:
  4084. val = 0.1
  4085. try:
  4086. val = float(self.defaults[dim]) * sfactor
  4087. except Exception as e:
  4088. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4089. self.defaults[dim] = float('%.4f' % val)
  4090. else:
  4091. val = 0.1
  4092. try:
  4093. val = float(self.defaults[dim]) * sfactor
  4094. except Exception as e:
  4095. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4096. self.defaults[dim] = val
  4097. # The scaling factor depending on choice of units.
  4098. factor = 1/25.4
  4099. if new_units == 'MM':
  4100. factor = 25.4
  4101. # Changing project units. Warn user.
  4102. msgbox = QtWidgets.QMessageBox()
  4103. msgbox.setWindowTitle(_("Toggle Units"))
  4104. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4105. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4106. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4107. "properties of all objects to be scaled accordingly.\nContinue?"))
  4108. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4109. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4110. msgbox.setDefaultButton(bt_ok)
  4111. msgbox.exec_()
  4112. response = msgbox.clickedButton()
  4113. if response == bt_ok:
  4114. if no_pref is False:
  4115. self.options_read_form()
  4116. scale_options(factor)
  4117. self.options_write_form()
  4118. self.defaults_read_form()
  4119. scale_defaults(factor)
  4120. self.defaults_write_form(fl_units=new_units)
  4121. # save the defaults to file, some may assume that the conversion is enough and it's not
  4122. self.on_save_button()
  4123. self.should_we_save = True
  4124. # change this only if the workspace is active
  4125. if self.defaults['global_workspace'] is True:
  4126. self.plotcanvas.draw_workspace()
  4127. # adjust the grid values on the main toolbar
  4128. dec = 6 if new_units == 'IN'else 4
  4129. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4130. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4131. if not self.ui.grid_gap_link_cb.isChecked():
  4132. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4133. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4134. for obj in self.collection.get_list():
  4135. obj.convert_units(new_units)
  4136. # make that the properties stored in the object are also updated
  4137. self.object_changed.emit(obj)
  4138. obj.build_ui()
  4139. current = self.collection.get_active()
  4140. if current is not None:
  4141. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4142. if not isinstance(current, FlatCAMGeometry):
  4143. current.to_form()
  4144. self.plot_all()
  4145. self.inform.emit('[success] %s: %s' %
  4146. (_("Converted units to"), new_units))
  4147. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4148. self.set_screen_units(new_units)
  4149. else:
  4150. # Undo toggling
  4151. self.toggle_units_ignore = True
  4152. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4153. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4154. else:
  4155. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4156. self.toggle_units_ignore = False
  4157. self.inform.emit('[WARNING_NOTCL]%s' %
  4158. _(" Units conversion cancelled."))
  4159. self.options_read_form()
  4160. self.defaults_read_form()
  4161. def on_toggle_units_click(self):
  4162. try:
  4163. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4164. except (TypeError, AttributeError):
  4165. pass
  4166. if self.defaults["units"] == 'MM':
  4167. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4168. else:
  4169. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4170. self.on_toggle_units(no_pref=True)
  4171. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4172. lambda: self.on_toggle_units(no_pref=False))
  4173. def on_fullscreen(self):
  4174. self.report_usage("on_fullscreen()")
  4175. if self.toggle_fscreen is False:
  4176. if sys.platform == 'win32':
  4177. self.ui.showFullScreen()
  4178. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4179. tb.setVisible(False)
  4180. self.ui.splitter_left.setVisible(False)
  4181. self.toggle_fscreen = True
  4182. else:
  4183. if sys.platform == 'win32':
  4184. self.ui.showNormal()
  4185. self.restore_toolbar_view()
  4186. self.ui.splitter_left.setVisible(True)
  4187. self.toggle_fscreen = False
  4188. def on_toggle_plotarea(self):
  4189. self.report_usage("on_toggle_plotarea()")
  4190. try:
  4191. name = self.ui.plot_tab_area.widget(0).objectName()
  4192. except AttributeError:
  4193. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4194. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4195. self.ui.plot_tab_area.protectTab(0)
  4196. return
  4197. if name != 'plotarea':
  4198. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4199. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4200. self.ui.plot_tab_area.protectTab(0)
  4201. else:
  4202. self.ui.plot_tab_area.closeTab(0)
  4203. def on_toggle_notebook(self):
  4204. if self.ui.splitter.sizes()[0] == 0:
  4205. self.ui.splitter.setSizes([1, 1])
  4206. else:
  4207. self.ui.splitter.setSizes([0, 1])
  4208. def on_toggle_axis(self):
  4209. self.report_usage("on_toggle_axis()")
  4210. if self.toggle_axis is False:
  4211. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4212. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4213. self.plotcanvas.redraw()
  4214. self.toggle_axis = True
  4215. else:
  4216. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4217. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4218. self.plotcanvas.redraw()
  4219. self.toggle_axis = False
  4220. def on_toggle_grid(self):
  4221. self.report_usage("on_toggle_grid()")
  4222. self.ui.grid_snap_btn.trigger()
  4223. def on_options_combo_change(self, sel):
  4224. """
  4225. Called when the combo box to choose between application defaults and
  4226. project option changes value. The corresponding variables are
  4227. copied to the UI.
  4228. :param sel: The option index that was chosen.
  4229. :return: None
  4230. """
  4231. # combo_sel = self.ui.notebook.combo_options.get_active()
  4232. App.log.debug("Options --> %s" % sel)
  4233. # form = [self.defaults_form, self.options_form][sel]
  4234. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4235. if sel == 0:
  4236. self.gen_form = self.ui.general_defaults_form
  4237. self.ger_form = self.ui.gerber_defaults_form
  4238. self.exc_form = self.ui.excellon_defaults_form
  4239. self.geo_form = self.ui.geometry_defaults_form
  4240. self.cnc_form = self.ui.cncjob_defaults_form
  4241. self.tools_form = self.ui.tools_defaults_form
  4242. self.fa_form = self.ui.fa_defaults_form
  4243. elif sel == 1:
  4244. self.gen_form = self.ui.general_options_form
  4245. self.ger_form = self.ui.gerber_options_form
  4246. self.exc_form = self.ui.excellon_options_form
  4247. self.geo_form = self.ui.geometry_options_form
  4248. self.cnc_form = self.ui.cncjob_options_form
  4249. self.tools_form = self.ui.tools_options_form
  4250. self.fa_form = self.ui.fa_options_form
  4251. else:
  4252. return
  4253. try:
  4254. self.ui.general_scroll_area.takeWidget()
  4255. except:
  4256. self.log.debug("Nothing to remove")
  4257. self.ui.general_scroll_area.setWidget(self.gen_form)
  4258. self.gen_form.show()
  4259. try:
  4260. self.ui.gerber_scroll_area.takeWidget()
  4261. except:
  4262. self.log.debug("Nothing to remove")
  4263. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4264. self.ger_form.show()
  4265. try:
  4266. self.ui.excellon_scroll_area.takeWidget()
  4267. except:
  4268. self.log.debug("Nothing to remove")
  4269. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4270. self.exc_form.show()
  4271. try:
  4272. self.ui.geometry_scroll_area.takeWidget()
  4273. except:
  4274. self.log.debug("Nothing to remove")
  4275. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4276. self.geo_form.show()
  4277. try:
  4278. self.ui.cncjob_scroll_area.takeWidget()
  4279. except:
  4280. self.log.debug("Nothing to remove")
  4281. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4282. self.cnc_form.show()
  4283. try:
  4284. self.ui.tools_scroll_area.takeWidget()
  4285. except:
  4286. self.log.debug("Nothing to remove")
  4287. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4288. self.tools_form.show()
  4289. try:
  4290. self.ui.fa_scroll_area.takeWidget()
  4291. except:
  4292. self.log.debug("Nothing to remove")
  4293. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4294. self.fa_form.show()
  4295. self.log.debug("Finished GUI form initialization.")
  4296. # self.options2form()
  4297. def on_excellon_defaults_button(self):
  4298. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4299. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4300. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4301. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4302. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4303. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4304. log.debug("Excellon app defaults loaded ...")
  4305. def on_excellon_options_button(self):
  4306. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4307. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4308. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4309. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4310. self.options_form_fields["excellon_zeros"].set_value('L')
  4311. self.options_form_fields["excellon_units"].set_value('INCH')
  4312. log.debug("Excellon options defaults loaded ...")
  4313. # Setting plot colors handlers
  4314. def on_pf_color_entry(self):
  4315. self.defaults['global_plot_fill'] = \
  4316. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4317. self.defaults['global_plot_fill'][7:9]
  4318. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4319. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4320. def on_pf_color_button(self):
  4321. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4322. c_dialog = QtWidgets.QColorDialog()
  4323. plot_fill_color = c_dialog.getColor(initial=current_color)
  4324. if plot_fill_color.isValid() is False:
  4325. return
  4326. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4327. "background-color:%s" % str(plot_fill_color.name()))
  4328. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4329. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4330. self.defaults['global_plot_fill'] = new_val
  4331. def on_pf_color_spinner(self):
  4332. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4333. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4334. self.defaults['global_plot_fill'] = \
  4335. self.defaults['global_plot_fill'][:7] + \
  4336. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4337. self.defaults['global_plot_line'] = \
  4338. self.defaults['global_plot_line'][:7] + \
  4339. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4340. def on_pf_color_slider(self):
  4341. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4342. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4343. def on_pl_color_entry(self):
  4344. self.defaults['global_plot_line'] = \
  4345. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4346. self.defaults['global_plot_line'][7:9]
  4347. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4348. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4349. def on_pl_color_button(self):
  4350. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4351. # print(current_color)
  4352. c_dialog = QtWidgets.QColorDialog()
  4353. plot_line_color = c_dialog.getColor(initial=current_color)
  4354. if plot_line_color.isValid() is False:
  4355. return
  4356. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4357. "background-color:%s" % str(plot_line_color.name()))
  4358. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4359. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4360. self.defaults['global_plot_line'] = new_val_line
  4361. # Setting selection colors (left - right) handlers
  4362. def on_sf_color_entry(self):
  4363. self.defaults['global_sel_fill'] = \
  4364. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4365. self.defaults['global_sel_fill'][7:9]
  4366. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4367. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4368. def on_sf_color_button(self):
  4369. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4370. c_dialog = QtWidgets.QColorDialog()
  4371. plot_fill_color = c_dialog.getColor(initial=current_color)
  4372. if plot_fill_color.isValid() is False:
  4373. return
  4374. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4375. "background-color:%s" % str(plot_fill_color.name()))
  4376. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4377. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4378. self.defaults['global_sel_fill'] = new_val
  4379. def on_sf_color_spinner(self):
  4380. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4381. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4382. self.defaults['global_sel_fill'] = \
  4383. self.defaults['global_sel_fill'][:7] + \
  4384. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4385. self.defaults['global_sel_line'] = \
  4386. self.defaults['global_sel_line'][:7] + \
  4387. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4388. def on_sf_color_slider(self):
  4389. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4390. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4391. def on_sl_color_entry(self):
  4392. self.defaults['global_sel_line'] = \
  4393. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4394. self.defaults['global_sel_line'][7:9]
  4395. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4396. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4397. def on_sl_color_button(self):
  4398. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4399. c_dialog = QtWidgets.QColorDialog()
  4400. plot_line_color = c_dialog.getColor(initial=current_color)
  4401. if plot_line_color.isValid() is False:
  4402. return
  4403. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4404. "background-color:%s" % str(plot_line_color.name()))
  4405. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4406. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4407. self.defaults['global_sel_line'] = new_val_line
  4408. # Setting selection colors (right - left) handlers
  4409. def on_alt_sf_color_entry(self):
  4410. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4411. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4412. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4413. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4414. def on_alt_sf_color_button(self):
  4415. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4416. c_dialog = QtWidgets.QColorDialog()
  4417. plot_fill_color = c_dialog.getColor(initial=current_color)
  4418. if plot_fill_color.isValid() is False:
  4419. return
  4420. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4421. "background-color:%s" % str(plot_fill_color.name()))
  4422. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4423. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4424. self.defaults['global_alt_sel_fill'] = new_val
  4425. def on_alt_sf_color_spinner(self):
  4426. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4427. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4428. self.defaults['global_alt_sel_fill'] = \
  4429. self.defaults['global_alt_sel_fill'][:7] + \
  4430. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4431. self.defaults['global_alt_sel_line'] = \
  4432. self.defaults['global_alt_sel_line'][:7] + \
  4433. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4434. def on_alt_sf_color_slider(self):
  4435. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4436. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4437. def on_alt_sl_color_entry(self):
  4438. self.defaults['global_alt_sel_line'] = \
  4439. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4440. self.defaults['global_alt_sel_line'][7:9]
  4441. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4442. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4443. def on_alt_sl_color_button(self):
  4444. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4445. c_dialog = QtWidgets.QColorDialog()
  4446. plot_line_color = c_dialog.getColor(initial=current_color)
  4447. if plot_line_color.isValid() is False:
  4448. return
  4449. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4450. "background-color:%s" % str(plot_line_color.name()))
  4451. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4452. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4453. self.defaults['global_alt_sel_line'] = new_val_line
  4454. # Setting Editor colors
  4455. def on_draw_color_entry(self):
  4456. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4457. .draw_color_entry.get_value()
  4458. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4459. "background-color:%s" % str(self.defaults['global_draw_color']))
  4460. def on_draw_color_button(self):
  4461. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4462. c_dialog = QtWidgets.QColorDialog()
  4463. draw_color = c_dialog.getColor(initial=current_color)
  4464. if draw_color.isValid() is False:
  4465. return
  4466. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4467. "background-color:%s" % str(draw_color.name()))
  4468. new_val = str(draw_color.name())
  4469. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4470. self.defaults['global_draw_color'] = new_val
  4471. def on_sel_draw_color_entry(self):
  4472. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4473. .sel_draw_color_entry.get_value()
  4474. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4475. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4476. def on_sel_draw_color_button(self):
  4477. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4478. c_dialog = QtWidgets.QColorDialog()
  4479. sel_draw_color = c_dialog.getColor(initial=current_color)
  4480. if sel_draw_color.isValid() is False:
  4481. return
  4482. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4483. "background-color:%s" % str(sel_draw_color.name()))
  4484. new_val_sel = str(sel_draw_color.name())
  4485. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4486. self.defaults['global_sel_draw_color'] = new_val_sel
  4487. def on_proj_color_entry(self):
  4488. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4489. .proj_color_entry.get_value()
  4490. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4491. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4492. def on_proj_color_button(self):
  4493. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4494. c_dialog = QtWidgets.QColorDialog()
  4495. proj_color = c_dialog.getColor(initial=current_color)
  4496. if proj_color.isValid() is False:
  4497. return
  4498. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4499. "background-color:%s" % str(proj_color.name()))
  4500. new_val_sel = str(proj_color.name())
  4501. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4502. self.defaults['global_proj_item_color'] = new_val_sel
  4503. def on_proj_color_dis_entry(self):
  4504. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4505. .proj_color_dis_entry.get_value()
  4506. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4507. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4508. def on_proj_color_dis_button(self):
  4509. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4510. c_dialog = QtWidgets.QColorDialog()
  4511. proj_color = c_dialog.getColor(initial=current_color)
  4512. if proj_color.isValid() is False:
  4513. return
  4514. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4515. "background-color:%s" % str(proj_color.name()))
  4516. new_val_sel = str(proj_color.name())
  4517. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4518. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4519. def on_annotation_fontcolor_entry(self):
  4520. self.defaults['cncjob_annotation_fontcolor'] = \
  4521. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  4522. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4523. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4524. def on_annotation_fontcolor_button(self):
  4525. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4526. c_dialog = QtWidgets.QColorDialog()
  4527. annotation_color = c_dialog.getColor(initial=current_color)
  4528. if annotation_color.isValid() is False:
  4529. return
  4530. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4531. "background-color:%s" % str(annotation_color.name()))
  4532. new_val_sel = str(annotation_color.name())
  4533. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4534. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4535. def on_splash_changed(self, state):
  4536. settings = QSettings("Open Source", "FlatCAM")
  4537. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  4538. # This will write the setting to the platform specific storage.
  4539. del settings
  4540. def on_notebook_tab_rmb_click(self, checked):
  4541. self.ui.notebook.set_detachable(val=checked)
  4542. self.defaults["global_tabs_detachable"] = checked
  4543. self.ui.plot_tab_area.set_detachable(val=checked)
  4544. self.defaults["global_tabs_detachable"] = checked
  4545. def on_deselect_all(self):
  4546. self.collection.set_all_inactive()
  4547. self.delete_selection_shape()
  4548. def on_workspace_modified(self):
  4549. self.save_defaults(silent=True)
  4550. self.plotcanvas.draw_workspace()
  4551. def on_workspace(self):
  4552. self.report_usage("on_workspace()")
  4553. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4554. self.plotcanvas.restore_workspace()
  4555. else:
  4556. self.plotcanvas.delete_workspace()
  4557. self.save_defaults(silent=True)
  4558. def on_workspace_menu(self):
  4559. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4560. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4561. else:
  4562. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4563. self.on_workspace()
  4564. def on_layout(self, index=None, lay=None):
  4565. self.report_usage("on_layout()")
  4566. if lay:
  4567. current_layout = lay
  4568. else:
  4569. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4570. settings = QSettings("Open Source", "FlatCAM")
  4571. settings.setValue('layout', current_layout)
  4572. # This will write the setting to the platform specific storage.
  4573. del settings
  4574. # first remove the toolbars:
  4575. try:
  4576. self.ui.removeToolBar(self.ui.toolbarfile)
  4577. self.ui.removeToolBar(self.ui.toolbargeo)
  4578. self.ui.removeToolBar(self.ui.toolbarview)
  4579. self.ui.removeToolBar(self.ui.toolbarshell)
  4580. self.ui.removeToolBar(self.ui.toolbartools)
  4581. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4582. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4583. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4584. self.ui.removeToolBar(self.ui.snap_toolbar)
  4585. self.ui.removeToolBar(self.ui.toolbarshell)
  4586. except Exception as e:
  4587. pass
  4588. if current_layout == 'standard':
  4589. # ## TOOLBAR INSTALLATION # ##
  4590. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4591. self.ui.toolbarfile.setObjectName('File_TB')
  4592. self.ui.addToolBar(self.ui.toolbarfile)
  4593. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4594. self.ui.toolbargeo.setObjectName('Edit_TB')
  4595. self.ui.addToolBar(self.ui.toolbargeo)
  4596. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4597. self.ui.toolbarview.setObjectName('View_TB')
  4598. self.ui.addToolBar(self.ui.toolbarview)
  4599. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4600. self.ui.toolbarshell.setObjectName('Shell_TB')
  4601. self.ui.addToolBar(self.ui.toolbarshell)
  4602. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4603. self.ui.toolbartools.setObjectName('Tools_TB')
  4604. self.ui.addToolBar(self.ui.toolbartools)
  4605. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4606. # self.ui.exc_edit_toolbar.setVisible(False)
  4607. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4608. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4609. self.ui.addToolBarBreak()
  4610. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4611. # self.ui.geo_edit_toolbar.setVisible(False)
  4612. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4613. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4614. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4615. # self.ui.grb_edit_toolbar.setVisible(False)
  4616. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4617. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4618. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4619. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4620. # self.ui.snap_toolbar.setMaximumHeight(30)
  4621. self.ui.addToolBar(self.ui.snap_toolbar)
  4622. self.ui.corner_snap_btn.setVisible(False)
  4623. self.ui.snap_magnet.setVisible(False)
  4624. elif current_layout == 'compact':
  4625. # ## TOOLBAR INSTALLATION # ##
  4626. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4627. self.ui.toolbarfile.setObjectName('File_TB')
  4628. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4629. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4630. self.ui.toolbargeo.setObjectName('Edit_TB')
  4631. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4632. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4633. self.ui.toolbarshell.setObjectName('Shell_TB')
  4634. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4635. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4636. self.ui.toolbartools.setObjectName('Tools_TB')
  4637. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4638. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4639. # self.ui.geo_edit_toolbar.setVisible(False)
  4640. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4641. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4642. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4643. self.ui.toolbarview.setObjectName('View_TB')
  4644. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  4645. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  4646. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4647. # self.ui.grb_edit_toolbar.setVisible(False)
  4648. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4649. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4650. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4651. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4652. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4653. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4654. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4655. self.ui.snap_toolbar.setMaximumHeight(30)
  4656. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4657. self.ui.corner_snap_btn.setVisible(True)
  4658. self.ui.snap_magnet.setVisible(True)
  4659. # add all the actions to the toolbars
  4660. self.ui.populate_toolbars()
  4661. # reconnect all the signals to the toolbar actions
  4662. self.connect_toolbar_signals()
  4663. self.ui.grid_snap_btn.setChecked(True)
  4664. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4665. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4666. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4667. self.ui.grid_gap_link_cb.setChecked(True)
  4668. def on_cnc_custom_parameters(self, signal_text):
  4669. if signal_text == 'Parameters':
  4670. return
  4671. else:
  4672. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4673. def on_save_button(self):
  4674. log.debug("App.on_save_button() --> Saving preferences to file.")
  4675. self.preferences_changed_flag = False
  4676. self.save_defaults(silent=False)
  4677. # load the defaults so they are updated into the app
  4678. self.load_defaults(filename='current_defaults')
  4679. # Re-fresh project options
  4680. self.on_options_app2project()
  4681. # save the notebook font size
  4682. settings = QSettings("Open Source", "FlatCAM")
  4683. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4684. settings.setValue('notebook_font_size', fsize)
  4685. # save the axis font size
  4686. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4687. settings.setValue('axis_font_size', g_fsize)
  4688. # This will write the setting to the platform specific storage.
  4689. del settings
  4690. def handlePrint(self):
  4691. self.report_usage("handlePrint()")
  4692. dialog = QtPrintSupport.QPrintDialog()
  4693. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4694. self.ui.code_editor.document().print_(dialog.printer())
  4695. def handlePreview(self):
  4696. self.report_usage("handlePreview()")
  4697. dialog = QtPrintSupport.QPrintPreviewDialog()
  4698. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4699. dialog.exec_()
  4700. def handleTextChanged(self):
  4701. # enable = not self.ui.code_editor.document().isEmpty()
  4702. # self.ui.buttonPrint.setEnabled(enable)
  4703. # self.ui.buttonPreview.setEnabled(enable)
  4704. pass
  4705. def handleOpen(self, filt=None):
  4706. self.report_usage("handleOpen()")
  4707. if filt:
  4708. _filter_ = filt
  4709. else:
  4710. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4711. "All Files (*.*)"
  4712. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4713. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4714. if path:
  4715. file = QtCore.QFile(path)
  4716. if file.open(QtCore.QIODevice.ReadOnly):
  4717. stream = QtCore.QTextStream(file)
  4718. self.gcode_edited = stream.readAll()
  4719. self.ui.code_editor.setPlainText(self.gcode_edited)
  4720. file.close()
  4721. def handleSaveGCode(self, name=None, filt=None):
  4722. self.report_usage("handleSaveGCode()")
  4723. if filt:
  4724. _filter_ = filt
  4725. else:
  4726. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4727. "All Files (*.*)"
  4728. if name:
  4729. obj_name = name
  4730. else:
  4731. try:
  4732. obj_name = self.collection.get_active().options['name']
  4733. except AttributeError:
  4734. obj_name = 'file'
  4735. if filt is None:
  4736. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4737. try:
  4738. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4739. caption=_("Export G-Code ..."),
  4740. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4741. filter=_filter_
  4742. )[0])
  4743. except TypeError:
  4744. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4745. if filename == "":
  4746. self.inform.emit('[WARNING_NOTCL] %s' %
  4747. _("Export Code cancelled."))
  4748. return
  4749. else:
  4750. try:
  4751. my_gcode = self.ui.code_editor.toPlainText()
  4752. with open(filename, 'w') as f:
  4753. for line in my_gcode:
  4754. f.write(line)
  4755. except FileNotFoundError:
  4756. self.inform.emit('[WARNING] %s' %
  4757. _("No such file or directory"))
  4758. return
  4759. except PermissionError:
  4760. self.inform.emit('[WARNING] %s' %
  4761. _("Permission denied, saving not possible.\n"
  4762. "Most likely another app is holding the file open and not accessible."))
  4763. return
  4764. # Just for adding it to the recent files list.
  4765. if self.defaults["global_open_style"] is False:
  4766. self.file_opened.emit("cncjob", filename)
  4767. self.file_saved.emit("cncjob", filename)
  4768. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  4769. def handleFindGCode(self):
  4770. self.report_usage("handleFindGCode()")
  4771. flags = QtGui.QTextDocument.FindCaseSensitively
  4772. text_to_be_found = self.ui.entryFind.get_value()
  4773. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4774. if r is False:
  4775. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4776. def handleReplaceGCode(self):
  4777. self.report_usage("handleReplaceGCode()")
  4778. old = self.ui.entryFind.get_value()
  4779. new = self.ui.entryReplace.get_value()
  4780. if self.ui.sel_all_cb.isChecked():
  4781. while True:
  4782. cursor = self.ui.code_editor.textCursor()
  4783. cursor.beginEditBlock()
  4784. flags = QtGui.QTextDocument.FindCaseSensitively
  4785. # self.ui.editor is the QPlainTextEdit
  4786. r = self.ui.code_editor.find(str(old), flags)
  4787. if r:
  4788. qc = self.ui.code_editor.textCursor()
  4789. if qc.hasSelection():
  4790. qc.insertText(new)
  4791. else:
  4792. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4793. break
  4794. # Mark end of undo block
  4795. cursor.endEditBlock()
  4796. else:
  4797. cursor = self.ui.code_editor.textCursor()
  4798. cursor.beginEditBlock()
  4799. qc = self.ui.code_editor.textCursor()
  4800. if qc.hasSelection():
  4801. qc.insertText(new)
  4802. # Mark end of undo block
  4803. cursor.endEditBlock()
  4804. def handleRunCode(self):
  4805. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  4806. # tries to print on a hidden widget, therefore show the dock if hidden
  4807. if self.ui.shell_dock.isHidden():
  4808. self.ui.shell_dock.show()
  4809. script_code = self.ui.code_editor.toPlainText()
  4810. # self.shell._sysShell.exec_command(script_code)
  4811. old_line = ''
  4812. for tcl_command_line in script_code.splitlines():
  4813. # do not process lines starting with '#' = comment and empty lines
  4814. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  4815. # id FlatCAM is run in Windows then replace all the slashes with
  4816. # the UNIX style slash that TCL understands
  4817. if sys.platform == 'win32':
  4818. if "open" in tcl_command_line:
  4819. tcl_command_line = tcl_command_line.replace('\\', '/')
  4820. if old_line != '':
  4821. new_command = old_line + tcl_command_line + '\n'
  4822. else:
  4823. new_command = tcl_command_line
  4824. # execute the actual Tcl command
  4825. try:
  4826. self.shell.open_proccessing() # Disables input box.
  4827. result = self.tcl.eval(str(new_command))
  4828. if result != 'None':
  4829. self.shell.append_output(result + '\n')
  4830. old_line = ''
  4831. except tk.TclError as e:
  4832. old_line = old_line + tcl_command_line + '\n'
  4833. if old_line != '':
  4834. # it means that the script finished with an error
  4835. result = self.tcl.eval("set errorInfo")
  4836. self.log.error("Exec command Exception: %s" % (result + '\n'))
  4837. self.shell.append_error('ERROR: ' + result + '\n')
  4838. else:
  4839. # success! plot all objects
  4840. self.plot_all()
  4841. self.shell.close_proccessing()
  4842. def on_tool_add_keypress(self):
  4843. # ## Current application units in Upper Case
  4844. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4845. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4846. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4847. if notebook_widget_name == 'selected_tab':
  4848. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4849. # Tool add works for Geometry only if Advanced is True in Preferences
  4850. if self.defaults["global_app_level"] == 'a':
  4851. tool_add_popup = FCInputDialog(title="New Tool ...",
  4852. text='Enter a Tool Diameter:',
  4853. min=0.0000, max=99.9999, decimals=4)
  4854. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4855. val, ok = tool_add_popup.get_value()
  4856. if ok:
  4857. if float(val) == 0:
  4858. self.inform.emit('[WARNING_NOTCL] %s' %
  4859. _("Please enter a tool diameter with non-zero value, in Float format."))
  4860. return
  4861. self.collection.get_active().on_tool_add(dia=float(val))
  4862. else:
  4863. self.inform.emit('[WARNING_NOTCL] %s...' %
  4864. _("Adding Tool cancelled"))
  4865. else:
  4866. msgbox = QtWidgets.QMessageBox()
  4867. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4868. "Go to Preferences -> General - Show Advanced Options."))
  4869. msgbox.setWindowTitle("Tool adding ...")
  4870. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4871. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4872. msgbox.setDefaultButton(bt_ok)
  4873. msgbox.exec_()
  4874. # work only if the notebook tab on focus is the Tools_Tab
  4875. if notebook_widget_name == 'tool_tab':
  4876. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4877. tool_add_popup = FCInputDialog(title="New Tool ...",
  4878. text='Enter a Tool Diameter:',
  4879. min=0.0000, max=99.9999, decimals=4)
  4880. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4881. val, ok = tool_add_popup.get_value()
  4882. # and only if the tool is NCC Tool
  4883. if tool_widget == self.ncclear_tool.toolName:
  4884. if ok:
  4885. if float(val) == 0:
  4886. self.inform.emit('[WARNING_NOTCL] %s' %
  4887. _("Please enter a tool diameter with non-zero value, in Float format."))
  4888. return
  4889. self.ncclear_tool.on_tool_add(dia=float(val))
  4890. else:
  4891. self.inform.emit('[WARNING_NOTCL] %s...' %
  4892. _("Adding Tool cancelled"))
  4893. # and only if the tool is Paint Area Tool
  4894. elif tool_widget == self.paint_tool.toolName:
  4895. if ok:
  4896. if float(val) == 0:
  4897. self.inform.emit('[WARNING_NOTCL] %s' %
  4898. _("Please enter a tool diameter with non-zero value, in Float format."))
  4899. return
  4900. self.paint_tool.on_tool_add(dia=float(val))
  4901. else:
  4902. self.inform.emit('[WARNING_NOTCL] %s...' %
  4903. _("Adding Tool cancelled"))
  4904. # and only if the tool is Solder Paste Dispensing Tool
  4905. elif tool_widget == self.paste_tool.toolName:
  4906. if ok:
  4907. if float(val) == 0:
  4908. self.inform.emit('[WARNING_NOTCL] %s' %
  4909. _("Please enter a tool diameter with non-zero value, in Float format."))
  4910. return
  4911. self.paste_tool.on_tool_add(dia=float(val))
  4912. else:
  4913. self.inform.emit('[WARNING_NOTCL] %s...' %
  4914. _("Adding Tool cancelled"))
  4915. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4916. # See description bellow.
  4917. def on_delete_keypress(self):
  4918. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4919. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4920. if notebook_widget_name == 'selected_tab':
  4921. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4922. self.collection.get_active().on_tool_delete()
  4923. # work only if the notebook tab on focus is the Tools_Tab
  4924. elif notebook_widget_name == 'tool_tab':
  4925. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4926. # and only if the tool is NCC Tool
  4927. if tool_widget == self.ncclear_tool.toolName:
  4928. self.ncclear_tool.on_tool_delete()
  4929. # and only if the tool is Paint Tool
  4930. elif tool_widget == self.paint_tool.toolName:
  4931. self.paint_tool.on_tool_delete()
  4932. # and only if the tool is Solder Paste Dispensing Tool
  4933. elif tool_widget == self.paste_tool.toolName:
  4934. self.paste_tool.on_tool_delete()
  4935. else:
  4936. self.on_delete()
  4937. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4938. # some screens you have to be careful where you hover with your mouse.
  4939. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4940. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4941. # Complicated, I know :)
  4942. def on_delete(self):
  4943. """
  4944. Delete the currently selected FlatCAMObjs.
  4945. :return: None
  4946. """
  4947. self.report_usage("on_delete()")
  4948. response = None
  4949. bt_ok = None
  4950. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4951. # a geometry object before we update it.
  4952. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4953. and self.grb_editor.editor_active is False:
  4954. if self.defaults["global_delete_confirmation"] is True:
  4955. msgbox = QtWidgets.QMessageBox()
  4956. msgbox.setWindowTitle(_("Delete objects"))
  4957. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4958. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4959. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4960. "the selected objects?"))
  4961. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4962. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4963. msgbox.setDefaultButton(bt_ok)
  4964. msgbox.exec_()
  4965. response = msgbox.clickedButton()
  4966. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4967. if self.collection.get_active():
  4968. self.log.debug("App.on_delete()")
  4969. while self.collection.get_active():
  4970. obj_active = self.collection.get_active()
  4971. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4972. if isinstance(obj_active, FlatCAMGerber):
  4973. for el in obj_active.mark_shapes:
  4974. obj_active.mark_shapes[el].clear(update=True)
  4975. obj_active.mark_shapes[el].enabled = False
  4976. # obj_active.mark_shapes[el] = None
  4977. del el
  4978. elif isinstance(obj_active, FlatCAMCNCjob):
  4979. try:
  4980. obj_active.annotation.clear(update=True)
  4981. obj_active.annotation.enabled = False
  4982. except AttributeError:
  4983. pass
  4984. self.delete_first_selected()
  4985. self.inform.emit('%s...' %
  4986. _("Object(s) deleted"))
  4987. # make sure that the selection shape is deleted, too
  4988. self.delete_selection_shape()
  4989. else:
  4990. self.inform.emit(_("Failed. No object(s) selected..."))
  4991. else:
  4992. self.inform.emit(_("Save the work in Editor and try again ..."))
  4993. def delete_first_selected(self):
  4994. # Keep this for later
  4995. try:
  4996. sel_obj = self.collection.get_active()
  4997. name = sel_obj.options["name"]
  4998. except AttributeError:
  4999. self.log.debug("Nothing selected for deletion")
  5000. return
  5001. # Remove from dictionary
  5002. self.collection.delete_active()
  5003. # Clear form
  5004. self.setup_component_editor()
  5005. self.inform.emit('%s: %s' %
  5006. (_("Object deleted"), name))
  5007. def on_set_origin(self):
  5008. """
  5009. Set the origin to the left mouse click position
  5010. :return: None
  5011. """
  5012. # display the message for the user
  5013. # and ask him to click on the desired position
  5014. self.report_usage("on_set_origin()")
  5015. def origin_replot():
  5016. def worker_task():
  5017. with self.proc_container.new('%s...' % _("Plotting")):
  5018. for obj in self.collection.get_list():
  5019. obj.plot()
  5020. self.plotcanvas.fit_view()
  5021. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5022. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5023. self.inform.emit(_('Click to set the origin ...'))
  5024. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5025. # first disconnect it as it may have been used by something else
  5026. try:
  5027. self.replot_signal.disconnect()
  5028. except TypeError:
  5029. pass
  5030. self.replot_signal[list].connect(origin_replot)
  5031. def on_set_zero_click(self, event):
  5032. # this function will be available only for mouse left click
  5033. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5034. if event.button == 1:
  5035. if self.grid_status() == True:
  5036. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5037. else:
  5038. pos = pos_canvas
  5039. x = 0 - pos[0]
  5040. y = 0 - pos[1]
  5041. def worker_task():
  5042. with self.proc_container.new(_("Setting Origin...")):
  5043. for obj in self.collection.get_list():
  5044. obj.offset((x, y))
  5045. self.object_changed.emit(obj)
  5046. # Update the object bounding box options
  5047. a, b, c, d = obj.bounds()
  5048. obj.options['xmin'] = a
  5049. obj.options['ymin'] = b
  5050. obj.options['xmax'] = c
  5051. obj.options['ymax'] = d
  5052. self.inform.emit('[success]%s...' %
  5053. _('Origin set'))
  5054. self.replot_signal.emit([])
  5055. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5056. self.should_we_save = True
  5057. def on_jump_to(self, custom_location=None, fit_center=True):
  5058. """
  5059. Jump to a location by setting the mouse cursor location
  5060. :return:
  5061. """
  5062. self.report_usage("on_jump_to()")
  5063. if not custom_location:
  5064. dia_box = Dialog_box(title=_("Jump to ..."),
  5065. label=_("Enter the coordinates in format X,Y:"),
  5066. icon=QtGui.QIcon('share/jump_to16.png'))
  5067. if dia_box.ok is True:
  5068. try:
  5069. location = eval(dia_box.location)
  5070. if not isinstance(location, tuple):
  5071. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5072. return
  5073. except:
  5074. return
  5075. else:
  5076. return
  5077. else:
  5078. location = custom_location
  5079. if fit_center:
  5080. self.plotcanvas.fit_center(loc=location)
  5081. cursor = QtGui.QCursor()
  5082. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5083. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5084. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5085. self.inform.emit('[success] %s' %
  5086. _("Done."))
  5087. return location
  5088. def on_copy_object(self):
  5089. self.report_usage("on_copy_object()")
  5090. def initialize(obj_init, app):
  5091. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5092. try:
  5093. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5094. except AttributeError:
  5095. pass
  5096. try:
  5097. obj_init.apertures = deepcopy(obj.apertures)
  5098. except AttributeError:
  5099. pass
  5100. try:
  5101. if obj.tools:
  5102. obj_init.tools = deepcopy(obj.tools)
  5103. except Exception as e:
  5104. log.debug("App.on_copy_object() --> %s" % str(e))
  5105. def initialize_excellon(obj_init, app):
  5106. obj_init.tools = deepcopy(obj.tools)
  5107. # drills are offset, so they need to be deep copied
  5108. obj_init.drills = deepcopy(obj.drills)
  5109. # slots are offset, so they need to be deep copied
  5110. obj_init.slots = deepcopy(obj.slots)
  5111. obj_init.create_geometry()
  5112. for obj in self.collection.get_selected():
  5113. obj_name = obj.options["name"]
  5114. try:
  5115. if isinstance(obj, FlatCAMExcellon):
  5116. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5117. elif isinstance(obj, FlatCAMGerber):
  5118. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5119. elif isinstance(obj, FlatCAMGeometry):
  5120. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5121. except Exception as e:
  5122. return "Operation failed: %s" % str(e)
  5123. def on_copy_object2(self, custom_name):
  5124. def initialize_geometry(obj_init, app):
  5125. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5126. try:
  5127. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5128. except AttributeError:
  5129. pass
  5130. try:
  5131. obj_init.apertures = deepcopy(obj.apertures)
  5132. except AttributeError:
  5133. pass
  5134. try:
  5135. if obj.tools:
  5136. obj_init.tools = deepcopy(obj.tools)
  5137. except Exception as e:
  5138. log.debug("on_copy_object2() --> %s" % str(e))
  5139. def initialize_gerber(obj_init, app):
  5140. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5141. obj_init.apertures = deepcopy(obj.apertures)
  5142. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5143. def initialize_excellon(obj_init, app):
  5144. obj_init.tools = deepcopy(obj.tools)
  5145. # drills are offset, so they need to be deep copied
  5146. obj_init.drills = deepcopy(obj.drills)
  5147. # slots are offset, so they need to be deep copied
  5148. obj_init.slots = deepcopy(obj.slots)
  5149. obj_init.create_geometry()
  5150. for obj in self.collection.get_selected():
  5151. obj_name = obj.options["name"]
  5152. try:
  5153. if isinstance(obj, FlatCAMExcellon):
  5154. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5155. elif isinstance(obj, FlatCAMGerber):
  5156. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5157. elif isinstance(obj, FlatCAMGeometry):
  5158. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5159. except Exception as e:
  5160. return "Operation failed: %s" % str(e)
  5161. def on_rename_object(self, text):
  5162. self.report_usage("on_rename_object()")
  5163. named_obj = self.collection.get_active()
  5164. for obj in named_obj:
  5165. if obj is list:
  5166. self.on_rename_object(text)
  5167. else:
  5168. try:
  5169. obj.options['name'] = text
  5170. except Exception as e:
  5171. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5172. def convert_any2geo(self):
  5173. self.report_usage("convert_any2geo()")
  5174. def initialize(obj_init, app):
  5175. obj_init.solid_geometry = obj.solid_geometry
  5176. try:
  5177. obj_init.follow_geometry = obj.follow_geometry
  5178. except AttributeError:
  5179. pass
  5180. try:
  5181. obj_init.apertures = obj.apertures
  5182. except AttributeError:
  5183. pass
  5184. try:
  5185. if obj.tools:
  5186. obj_init.tools = obj.tools
  5187. except AttributeError:
  5188. pass
  5189. def initialize_excellon(obj_init, app):
  5190. # objs = self.collection.get_selected()
  5191. # FlatCAMGeometry.merge(objs, obj)
  5192. solid_geo = []
  5193. for tool in obj.tools:
  5194. for geo in obj.tools[tool]['solid_geometry']:
  5195. solid_geo.append(geo)
  5196. obj_init.solid_geometry = deepcopy(solid_geo)
  5197. if not self.collection.get_selected():
  5198. log.warning("App.convert_any2geo --> No object selected")
  5199. self.inform.emit('[WARNING_NOTCL] %s' %
  5200. _("No object is selected. Select an object and try again."))
  5201. return
  5202. for obj in self.collection.get_selected():
  5203. obj_name = obj.options["name"]
  5204. try:
  5205. if isinstance(obj, FlatCAMExcellon):
  5206. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5207. else:
  5208. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5209. except Exception as e:
  5210. return "Operation failed: %s" % str(e)
  5211. def convert_any2gerber(self):
  5212. self.report_usage("convert_any2gerber()")
  5213. def initialize_geometry(obj_init, app):
  5214. apertures = {}
  5215. apid = 0
  5216. apertures[str(apid)] = {}
  5217. apertures[str(apid)]['geometry'] = []
  5218. for obj_orig in obj.solid_geometry:
  5219. new_elem = dict()
  5220. new_elem['solid'] = obj_orig
  5221. new_elem['follow'] = obj_orig.exterior
  5222. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5223. apertures[str(apid)]['size'] = 0.0
  5224. apertures[str(apid)]['type'] = 'C'
  5225. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5226. obj_init.apertures = deepcopy(apertures)
  5227. def initialize_excellon(obj_init, app):
  5228. apertures = {}
  5229. apid = 10
  5230. for tool in obj.tools:
  5231. apertures[str(apid)] = {}
  5232. apertures[str(apid)]['geometry'] = []
  5233. for geo in obj.tools[tool]['solid_geometry']:
  5234. new_el = dict()
  5235. new_el['solid'] = geo
  5236. new_el['follow'] = geo.exterior
  5237. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5238. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5239. apertures[str(apid)]['type'] = 'C'
  5240. apid += 1
  5241. # create solid_geometry
  5242. solid_geometry = []
  5243. for apid in apertures:
  5244. for geo_el in apertures[apid]['geometry']:
  5245. solid_geometry.append(geo_el['solid'])
  5246. solid_geometry = MultiPolygon(solid_geometry)
  5247. solid_geometry = solid_geometry.buffer(0.0000001)
  5248. obj_init.solid_geometry = deepcopy(solid_geometry)
  5249. obj_init.apertures = deepcopy(apertures)
  5250. # clear the working objects (perhaps not necessary due of Python GC)
  5251. apertures.clear()
  5252. if not self.collection.get_selected():
  5253. log.warning("App.convert_any2gerber --> No object selected")
  5254. self.inform.emit('[WARNING_NOTCL] %s' %
  5255. _("No object is selected. Select an object and try again."))
  5256. return
  5257. for obj in self.collection.get_selected():
  5258. obj_name = obj.options["name"]
  5259. try:
  5260. if isinstance(obj, FlatCAMExcellon):
  5261. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5262. elif isinstance(obj, FlatCAMGeometry):
  5263. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5264. else:
  5265. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5266. except Exception as e:
  5267. return "Operation failed: %s" % str(e)
  5268. def abort_all_tasks(self):
  5269. if self.abort_flag is False:
  5270. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5271. self.abort_flag = True
  5272. def app_is_idle(self):
  5273. if self.abort_flag:
  5274. self.inform.emit('[WARNING_NOTCL] %s' %
  5275. _("The current task was gracefully closed on user request..."))
  5276. self.abort_flag = False
  5277. def on_selectall(self):
  5278. self.report_usage("on_selectall()")
  5279. # delete the possible selection box around a possible selected object
  5280. self.delete_selection_shape()
  5281. for name in self.collection.get_names():
  5282. self.collection.set_active(name)
  5283. curr_sel_obj = self.collection.get_by_name(name)
  5284. # create the selection box around the selected object
  5285. if self.defaults['global_selection_shape'] is True:
  5286. self.draw_selection_shape(curr_sel_obj)
  5287. def on_preferences(self):
  5288. # add the tab if it was closed
  5289. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5290. # delete the absolute and relative position and messages in the infobar
  5291. self.ui.position_label.setText("")
  5292. self.ui.rel_position_label.setText("")
  5293. # Switch plot_area to preferences page
  5294. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5295. self.ui.show()
  5296. # this disconnect() is done so the slot will be connected only once
  5297. try:
  5298. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5299. except (TypeError, AttributeError):
  5300. pass
  5301. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5302. # detect changes in the preferences
  5303. for idx in range(self.ui.pref_tab_area.count()):
  5304. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5305. try:
  5306. try:
  5307. tb.textEdited.disconnect(self.on_preferences_edited)
  5308. except (TypeError, AttributeError):
  5309. pass
  5310. tb.textEdited.connect(self.on_preferences_edited)
  5311. except AttributeError:
  5312. pass
  5313. try:
  5314. try:
  5315. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5316. except (TypeError, AttributeError):
  5317. pass
  5318. tb.modificationChanged.connect(self.on_preferences_edited)
  5319. except AttributeError:
  5320. pass
  5321. try:
  5322. try:
  5323. tb.toggled.disconnect(self.on_preferences_edited)
  5324. except (TypeError, AttributeError):
  5325. pass
  5326. tb.toggled.connect(self.on_preferences_edited)
  5327. except AttributeError:
  5328. pass
  5329. try:
  5330. try:
  5331. tb.valueChanged.disconnect(self.on_preferences_edited)
  5332. except (TypeError, AttributeError):
  5333. pass
  5334. tb.valueChanged.connect(self.on_preferences_edited)
  5335. except AttributeError:
  5336. pass
  5337. try:
  5338. try:
  5339. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5340. except (TypeError, AttributeError):
  5341. pass
  5342. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5343. except AttributeError:
  5344. pass
  5345. def on_preferences_edited(self):
  5346. self.inform.emit('[WARNING_NOTCL] %s' %
  5347. _("Preferences edited but not saved."))
  5348. self.preferences_changed_flag = True
  5349. def on_preferences_closed(self):
  5350. # disconnect
  5351. for idx in range(self.ui.pref_tab_area.count()):
  5352. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5353. try:
  5354. tb.textEdited.disconnect(self.on_preferences_edited)
  5355. except (TypeError, AttributeError):
  5356. pass
  5357. try:
  5358. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5359. except (TypeError, AttributeError):
  5360. pass
  5361. try:
  5362. tb.toggled.disconnect(self.on_preferences_edited)
  5363. except (TypeError, AttributeError):
  5364. pass
  5365. try:
  5366. tb.valueChanged.disconnect(self.on_preferences_edited)
  5367. except (TypeError, AttributeError):
  5368. pass
  5369. try:
  5370. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5371. except (TypeError, AttributeError):
  5372. pass
  5373. if self.preferences_changed_flag is True:
  5374. msgbox = QtWidgets.QMessageBox()
  5375. msgbox.setText(_("One or more values are changed.\n"
  5376. "Do you want to save the Preferences?"))
  5377. msgbox.setWindowTitle(_("Save Preferences"))
  5378. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5379. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5380. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5381. msgbox.setDefaultButton(bt_yes)
  5382. msgbox.exec_()
  5383. response = msgbox.clickedButton()
  5384. if response == bt_yes:
  5385. self.on_save_button()
  5386. self.inform.emit('[success] %s' %
  5387. _("Preferences saved."))
  5388. else:
  5389. self.preferences_changed_flag = False
  5390. return
  5391. def on_flipy(self):
  5392. self.report_usage("on_flipy()")
  5393. obj_list = self.collection.get_selected()
  5394. xminlist = []
  5395. yminlist = []
  5396. xmaxlist = []
  5397. ymaxlist = []
  5398. if not obj_list:
  5399. self.inform.emit('[WARNING_NOTCL] %s' %
  5400. _("No object selected to Flip on Y axis."))
  5401. else:
  5402. try:
  5403. # first get a bounding box to fit all
  5404. for obj in obj_list:
  5405. xmin, ymin, xmax, ymax = obj.bounds()
  5406. xminlist.append(xmin)
  5407. yminlist.append(ymin)
  5408. xmaxlist.append(xmax)
  5409. ymaxlist.append(ymax)
  5410. # get the minimum x,y and maximum x,y for all objects selected
  5411. xminimal = min(xminlist)
  5412. yminimal = min(yminlist)
  5413. xmaximal = max(xmaxlist)
  5414. ymaximal = max(ymaxlist)
  5415. px = 0.5 * (xminimal + xmaximal)
  5416. py = 0.5 * (yminimal + ymaximal)
  5417. # execute mirroring
  5418. for obj in obj_list:
  5419. obj.mirror('X', [px, py])
  5420. obj.plot()
  5421. self.object_changed.emit(obj)
  5422. self.inform.emit('[success] %s' %
  5423. _("Flip on Y axis done."))
  5424. except Exception as e:
  5425. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5426. (_("Flip action was not executed."), str(e)))
  5427. return
  5428. def on_flipx(self):
  5429. self.report_usage("on_flipx()")
  5430. obj_list = self.collection.get_selected()
  5431. xminlist = []
  5432. yminlist = []
  5433. xmaxlist = []
  5434. ymaxlist = []
  5435. if not obj_list:
  5436. self.inform.emit('[WARNING_NOTCL] %s' %
  5437. _("No object selected to Flip on X axis."))
  5438. else:
  5439. try:
  5440. # first get a bounding box to fit all
  5441. for obj in obj_list:
  5442. xmin, ymin, xmax, ymax = obj.bounds()
  5443. xminlist.append(xmin)
  5444. yminlist.append(ymin)
  5445. xmaxlist.append(xmax)
  5446. ymaxlist.append(ymax)
  5447. # get the minimum x,y and maximum x,y for all objects selected
  5448. xminimal = min(xminlist)
  5449. yminimal = min(yminlist)
  5450. xmaximal = max(xmaxlist)
  5451. ymaximal = max(ymaxlist)
  5452. px = 0.5 * (xminimal + xmaximal)
  5453. py = 0.5 * (yminimal + ymaximal)
  5454. # execute mirroring
  5455. for obj in obj_list:
  5456. obj.mirror('Y', [px, py])
  5457. obj.plot()
  5458. self.object_changed.emit(obj)
  5459. self.inform.emit('[success] %s' %
  5460. _("Flip on X axis done."))
  5461. except Exception as e:
  5462. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5463. (_("Flip action was not executed."), str(e)))
  5464. return
  5465. def on_rotate(self, silent=False, preset=None):
  5466. self.report_usage("on_rotate()")
  5467. obj_list = self.collection.get_selected()
  5468. xminlist = []
  5469. yminlist = []
  5470. xmaxlist = []
  5471. ymaxlist = []
  5472. if not obj_list:
  5473. self.inform.emit('[WARNING_NOTCL] %s' %
  5474. _("No object selected to Rotate."))
  5475. else:
  5476. if silent is False:
  5477. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5478. min=-360, max=360, decimals=4,
  5479. init_val=float(self.defaults['tools_transform_rotate']))
  5480. num, ok = rotatebox.get_value()
  5481. else:
  5482. num = preset
  5483. ok = True
  5484. if ok:
  5485. try:
  5486. # first get a bounding box to fit all
  5487. for obj in obj_list:
  5488. xmin, ymin, xmax, ymax = obj.bounds()
  5489. xminlist.append(xmin)
  5490. yminlist.append(ymin)
  5491. xmaxlist.append(xmax)
  5492. ymaxlist.append(ymax)
  5493. # get the minimum x,y and maximum x,y for all objects selected
  5494. xminimal = min(xminlist)
  5495. yminimal = min(yminlist)
  5496. xmaximal = max(xmaxlist)
  5497. ymaximal = max(ymaxlist)
  5498. px = 0.5 * (xminimal + xmaximal)
  5499. py = 0.5 * (yminimal + ymaximal)
  5500. for sel_obj in obj_list:
  5501. sel_obj.rotate(-float(num), point=(px, py))
  5502. sel_obj.plot()
  5503. self.object_changed.emit(sel_obj)
  5504. self.inform.emit('[success] %s' %
  5505. _("Rotation done."))
  5506. except Exception as e:
  5507. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5508. (_("Rotation movement was not executed."), str(e)))
  5509. return
  5510. def on_skewx(self):
  5511. self.report_usage("on_skewx()")
  5512. obj_list = self.collection.get_selected()
  5513. xminlist = []
  5514. yminlist = []
  5515. if not obj_list:
  5516. self.inform.emit('[WARNING_NOTCL] %s' %
  5517. _("No object selected to Skew/Shear on X axis."))
  5518. else:
  5519. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5520. min=-360, max=360, decimals=4,
  5521. init_val=float(self.defaults['tools_transform_skew_x']))
  5522. num, ok = skewxbox.get_value()
  5523. if ok:
  5524. # first get a bounding box to fit all
  5525. for obj in obj_list:
  5526. xmin, ymin, xmax, ymax = obj.bounds()
  5527. xminlist.append(xmin)
  5528. yminlist.append(ymin)
  5529. # get the minimum x,y and maximum x,y for all objects selected
  5530. xminimal = min(xminlist)
  5531. yminimal = min(yminlist)
  5532. for obj in obj_list:
  5533. obj.skew(num, 0, point=(xminimal, yminimal))
  5534. obj.plot()
  5535. self.object_changed.emit(obj)
  5536. self.inform.emit('[success] %s' %
  5537. _("Skew on X axis done."))
  5538. def on_skewy(self):
  5539. self.report_usage("on_skewy()")
  5540. obj_list = self.collection.get_selected()
  5541. xminlist = []
  5542. yminlist = []
  5543. if not obj_list:
  5544. self.inform.emit('[WARNING_NOTCL] %s' %
  5545. _("No object selected to Skew/Shear on Y axis."))
  5546. else:
  5547. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5548. min=-360, max=360, decimals=4,
  5549. init_val=float(self.defaults['tools_transform_skew_y']))
  5550. num, ok = skewybox.get_value()
  5551. if ok:
  5552. # first get a bounding box to fit all
  5553. for obj in obj_list:
  5554. xmin, ymin, xmax, ymax = obj.bounds()
  5555. xminlist.append(xmin)
  5556. yminlist.append(ymin)
  5557. # get the minimum x,y and maximum x,y for all objects selected
  5558. xminimal = min(xminlist)
  5559. yminimal = min(yminlist)
  5560. for obj in obj_list:
  5561. obj.skew(0, num, point=(xminimal, yminimal))
  5562. obj.plot()
  5563. self.object_changed.emit(obj)
  5564. self.inform.emit('[success] %s' %
  5565. _("Skew on Y axis done."))
  5566. def on_plots_updated(self):
  5567. """
  5568. Callback used to report when the plots have changed.
  5569. Adjust axes and zooms to fit.
  5570. :return: None
  5571. """
  5572. self.plotcanvas.update() # TODO: Need update canvas?
  5573. self.on_zoom_fit(None)
  5574. self.collection.update_view()
  5575. # self.inform.emit(_("Plots updated ..."))
  5576. # TODO: Rework toolbar 'clear', 'replot' functions
  5577. def on_toolbar_replot(self):
  5578. """
  5579. Callback for toolbar button. Re-plots all objects.
  5580. :return: None
  5581. """
  5582. self.report_usage("on_toolbar_replot")
  5583. self.log.debug("on_toolbar_replot()")
  5584. try:
  5585. self.collection.get_active().read_form()
  5586. except AttributeError:
  5587. self.log.debug("on_toolbar_replot(): AttributeError")
  5588. pass
  5589. self.plot_all()
  5590. def on_row_activated(self, index):
  5591. if index.isValid():
  5592. if index.internalPointer().parent_item != self.collection.root_item:
  5593. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5594. self.collection.on_item_activated(index)
  5595. def grid_status(self):
  5596. if self.ui.grid_snap_btn.isChecked():
  5597. return True
  5598. else:
  5599. return False
  5600. def populate_cmenu_grids(self):
  5601. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5602. self.ui.cmenu_gridmenu.clear()
  5603. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5604. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5605. grid_toggle.setCheckable(True)
  5606. if self.grid_status() == True:
  5607. grid_toggle.setChecked(True)
  5608. else:
  5609. grid_toggle.setChecked(False)
  5610. self.ui.cmenu_gridmenu.addSeparator()
  5611. for grid in sorted_list:
  5612. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5613. action.triggered.connect(self.set_grid)
  5614. self.ui.cmenu_gridmenu.addSeparator()
  5615. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5616. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5617. grid_add.triggered.connect(self.on_grid_add)
  5618. grid_delete.triggered.connect(self.on_grid_delete)
  5619. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5620. def set_grid(self):
  5621. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5622. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5623. def on_grid_add(self):
  5624. # ## Current application units in lower Case
  5625. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5626. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5627. text=_('Enter a Grid Value:'),
  5628. min=0.0000, max=99.9999, decimals=4)
  5629. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5630. val, ok = grid_add_popup.get_value()
  5631. if ok:
  5632. if float(val) == 0:
  5633. self.inform.emit('[WARNING_NOTCL] %s' %
  5634. _("Please enter a grid value with non-zero value, in Float format."))
  5635. return
  5636. else:
  5637. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5638. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5639. self.inform.emit('[success] %s...' %
  5640. _("New Grid added"))
  5641. else:
  5642. self.inform.emit('[WARNING_NOTCL] %s...' %
  5643. _("Grid already exists"))
  5644. else:
  5645. self.inform.emit('[WARNING_NOTCL] %s...' %
  5646. _("Adding New Grid cancelled"))
  5647. def on_grid_delete(self):
  5648. # ## Current application units in lower Case
  5649. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5650. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5651. text='Enter a Grid Value:',
  5652. min=0.0000, max=99.9999, decimals=4)
  5653. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5654. val, ok = grid_del_popup.get_value()
  5655. if ok:
  5656. if float(val) == 0:
  5657. self.inform.emit('[WARNING_NOTCL] %s' %
  5658. _("Please enter a grid value with non-zero value, in Float format."))
  5659. return
  5660. else:
  5661. try:
  5662. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5663. except ValueError:
  5664. self.inform.emit('[ERROR_NOTCL]%s...' %
  5665. _(" Grid Value does not exist"))
  5666. return
  5667. self.inform.emit('[success] %s...' %
  5668. _("Grid Value deleted"))
  5669. else:
  5670. self.inform.emit('[WARNING_NOTCL] %s...' %
  5671. _("Delete Grid value cancelled"))
  5672. def on_shortcut_list(self):
  5673. self.report_usage("on_shortcut_list()")
  5674. # add the tab if it was closed
  5675. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5676. # delete the absolute and relative position and messages in the infobar
  5677. self.ui.position_label.setText("")
  5678. self.ui.rel_position_label.setText("")
  5679. # Switch plot_area to preferences page
  5680. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5681. self.ui.show()
  5682. def on_select_tab(self, name):
  5683. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5684. if self.ui.splitter.sizes()[0] == 0:
  5685. self.ui.splitter.setSizes([1, 1])
  5686. else:
  5687. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5688. self.ui.splitter.setSizes([0, 1])
  5689. if name == 'project':
  5690. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5691. elif name == 'selected':
  5692. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5693. elif name == 'tool':
  5694. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5695. def on_copy_name(self):
  5696. self.report_usage("on_copy_name()")
  5697. obj = self.collection.get_active()
  5698. try:
  5699. name = obj.options["name"]
  5700. except AttributeError:
  5701. log.debug("on_copy_name() --> No object selected to copy it's name")
  5702. self.inform.emit('[WARNING_NOTCL]%s' %
  5703. _(" No object selected to copy it's name"))
  5704. return
  5705. self.clipboard.setText(name)
  5706. self.inform.emit(_("Name copied on clipboard ..."))
  5707. def on_mouse_click_over_plot(self, event):
  5708. """
  5709. Default actions are:
  5710. :param event: Contains information about the event, like which button
  5711. was clicked, the pixel coordinates and the axes coordinates.
  5712. :return: None
  5713. """
  5714. self.pos = []
  5715. # So it can receive key presses
  5716. self.plotcanvas.native.setFocus()
  5717. # Set the mouse button for panning
  5718. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5719. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5720. if self.grid_status() == True:
  5721. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5722. self.app_cursor.enabled = True
  5723. else:
  5724. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5725. self.app_cursor.enabled = False
  5726. try:
  5727. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5728. if event.button == 1:
  5729. # Reset here the relative coordinates so there is a new reference on the click position
  5730. if self.rel_point1 is None:
  5731. self.rel_point1 = self.pos
  5732. else:
  5733. self.rel_point2 = copy(self.rel_point1)
  5734. self.rel_point1 = self.pos
  5735. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5736. if modifiers == QtCore.Qt.ShiftModifier:
  5737. # do not auto open the Project Tab
  5738. self.click_noproject = True
  5739. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5740. self.inform.emit('[success] %s' %
  5741. _("Coordinates copied to clipboard."))
  5742. return
  5743. self.on_mouse_move_over_plot(event, origin_click=True)
  5744. except Exception as e:
  5745. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5746. def on_double_click_over_plot(self, event):
  5747. self.doubleclick = True
  5748. def on_mouse_move_over_plot(self, event, origin_click=None):
  5749. """
  5750. Callback for the mouse motion event over the plot.
  5751. :param event: Contains information about the event.
  5752. :param origin_click
  5753. :return: None
  5754. """
  5755. # So it can receive key presses
  5756. self.plotcanvas.native.setFocus()
  5757. self.pos_jump = event.pos
  5758. self.ui.popMenu.mouse_is_panning = False
  5759. if not origin_click:
  5760. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5761. if event.button == 2 and event.is_dragging == 1:
  5762. self.ui.popMenu.mouse_is_panning = True
  5763. return
  5764. if self.rel_point1 is not None:
  5765. try: # May fail in case mouse not within axes
  5766. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5767. if self.grid_status() == True:
  5768. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5769. self.app_cursor.enabled = True
  5770. # Update cursor
  5771. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5772. else:
  5773. pos = (pos_canvas[0], pos_canvas[1])
  5774. self.app_cursor.enabled = False
  5775. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5776. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5777. dx = pos[0] - self.rel_point1[0]
  5778. dy = pos[1] - self.rel_point1[1]
  5779. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5780. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5781. self.mouse = [pos[0], pos[1]]
  5782. # if the mouse is moved and the LMB is clicked then the action is a selection
  5783. if event.is_dragging == 1 and event.button == 1:
  5784. self.delete_selection_shape()
  5785. if dx < 0:
  5786. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5787. face_color=self.defaults['global_alt_sel_fill'])
  5788. self.selection_type = False
  5789. else:
  5790. self.draw_moving_selection_shape(self.pos, pos)
  5791. self.selection_type = True
  5792. # hover effect - enabled in Preferences -> General -> GUI Settings
  5793. if self.defaults['global_hover']:
  5794. for obj in self.collection.get_list():
  5795. try:
  5796. # select the object(s) only if it is enabled (plotted)
  5797. if obj.options['plot']:
  5798. if obj not in self.collection.get_selected():
  5799. poly_obj = Polygon(
  5800. [(obj.options['xmin'], obj.options['ymin']),
  5801. (obj.options['xmax'], obj.options['ymin']),
  5802. (obj.options['xmax'], obj.options['ymax']),
  5803. (obj.options['xmin'], obj.options['ymax'])]
  5804. )
  5805. if Point(pos).within(poly_obj):
  5806. if obj.isHovering is False:
  5807. obj.isHovering = True
  5808. obj.notHovering = True
  5809. # create the selection box around the selected object
  5810. self.draw_hover_shape(obj, color='#d1e0e0')
  5811. else:
  5812. if obj.notHovering is True:
  5813. obj.notHovering = False
  5814. obj.isHovering = False
  5815. self.delete_hover_shape()
  5816. except:
  5817. # the Exception here will happen if we try to select on screen and we have an
  5818. # newly (and empty) just created Geometry or Excellon object that do not have the
  5819. # xmin, xmax, ymin, ymax options.
  5820. # In this case poly_obj creation (see above) will fail
  5821. pass
  5822. except:
  5823. self.ui.position_label.setText("")
  5824. self.ui.rel_position_label.setText("")
  5825. self.mouse = None
  5826. def on_mouse_click_release_over_plot(self, event):
  5827. """
  5828. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5829. and has been registered in ''self.__init__()''.
  5830. :param event: contains information about the event.
  5831. :return:
  5832. """
  5833. pos = 0, 0
  5834. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5835. if self.grid_status() == True:
  5836. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5837. else:
  5838. pos = (pos_canvas[0], pos_canvas[1])
  5839. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5840. # canvas menu
  5841. if event.button == 2: # right click
  5842. if self.ui.popMenu.mouse_is_panning is False:
  5843. self.cursor = QtGui.QCursor()
  5844. self.populate_cmenu_grids()
  5845. self.ui.popMenu.popup(self.cursor.pos())
  5846. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5847. # selection and then select a type of selection ("enclosing" or "touching")
  5848. try:
  5849. if event.button == 1: # left click
  5850. if self.doubleclick is True:
  5851. self.doubleclick = False
  5852. if self.collection.get_selected():
  5853. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5854. if self.ui.splitter.sizes()[0] == 0:
  5855. self.ui.splitter.setSizes([1, 1])
  5856. # delete the selection shape(S) as it may be in the way
  5857. self.delete_selection_shape()
  5858. self.delete_hover_shape()
  5859. else:
  5860. if self.selection_type is not None:
  5861. self.selection_area_handler(self.pos, pos, self.selection_type)
  5862. self.selection_type = None
  5863. else:
  5864. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5865. if key_modifier == QtCore.Qt.ShiftModifier:
  5866. mod_key = 'Shift'
  5867. elif key_modifier == QtCore.Qt.ControlModifier:
  5868. mod_key = 'Control'
  5869. else:
  5870. mod_key = None
  5871. if mod_key == self.defaults["global_mselect_key"]:
  5872. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5873. # deselect, and if it's not selected then it will be selected
  5874. # If there is no active command (self.command_active is None) then we check if we clicked
  5875. # on a object by checking the bounding limits against mouse click position
  5876. if self.command_active is None:
  5877. self.select_objects(key='CTRL')
  5878. self.delete_hover_shape()
  5879. else:
  5880. # If there is no active command (self.command_active is None) then we check if we clicked
  5881. # on a object by checking the bounding limits against mouse click position
  5882. if self.command_active is None:
  5883. self.select_objects()
  5884. self.delete_hover_shape()
  5885. except Exception as e:
  5886. log.warning("Error: %s" % str(e))
  5887. return
  5888. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5889. """
  5890. :param start_pos: mouse position when the selection LMB click was done
  5891. :param end_pos: mouse position when the left mouse button is released
  5892. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5893. :return:
  5894. """
  5895. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5896. self.delete_selection_shape()
  5897. for obj in self.collection.get_list():
  5898. try:
  5899. # select the object(s) only if it is enabled (plotted)
  5900. if obj.options['plot']:
  5901. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5902. (obj.options['xmax'], obj.options['ymin']),
  5903. (obj.options['xmax'], obj.options['ymax']),
  5904. (obj.options['xmin'], obj.options['ymax'])])
  5905. if sel_type is True:
  5906. if poly_obj.within(poly_selection):
  5907. # create the selection box around the selected object
  5908. if self.defaults['global_selection_shape'] is True:
  5909. self.draw_selection_shape(obj)
  5910. self.collection.set_active(obj.options['name'])
  5911. else:
  5912. if poly_selection.intersects(poly_obj):
  5913. # create the selection box around the selected object
  5914. if self.defaults['global_selection_shape'] is True:
  5915. self.draw_selection_shape(obj)
  5916. self.collection.set_active(obj.options['name'])
  5917. except Exception as e:
  5918. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5919. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5920. # In this case poly_obj creation (see above) will fail
  5921. log.debug("App.selection_area_handler() --> %s" % str(e))
  5922. def select_objects(self, key=None):
  5923. # list where we store the overlapped objects under our mouse left click position
  5924. objects_under_the_click_list = []
  5925. # Populate the list with the overlapped objects on the click position
  5926. curr_x, curr_y = self.pos
  5927. for obj in self.all_objects_list:
  5928. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5929. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5930. if obj.options['name'] not in objects_under_the_click_list:
  5931. if obj.options['plot']:
  5932. # add objects to the objects_under_the_click list only if the object is plotted
  5933. # (active and not disabled)
  5934. objects_under_the_click_list.append(obj.options['name'])
  5935. try:
  5936. # If there is no element in the overlapped objects list then make everyone inactive
  5937. # because we selected "nothing"
  5938. if not objects_under_the_click_list:
  5939. self.collection.set_all_inactive()
  5940. # delete the possible selection box around a possible selected object
  5941. self.delete_selection_shape()
  5942. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5943. # only when working on App
  5944. if self.call_source == 'app':
  5945. if self.click_noproject is False:
  5946. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5947. else:
  5948. # restore auto open the Project Tab
  5949. self.click_noproject = False
  5950. # delete any text in the status bar, implicitly the last object name that was selected
  5951. self.inform.emit("")
  5952. else:
  5953. self.call_source = 'app'
  5954. else:
  5955. # case when there is only an object under the click and we toggle it
  5956. if len(objects_under_the_click_list) == 1:
  5957. if self.collection.get_active() is None:
  5958. self.collection.set_active(objects_under_the_click_list[0])
  5959. # create the selection box around the selected object
  5960. curr_sel_obj = self.collection.get_active()
  5961. if self.defaults['global_selection_shape'] is True:
  5962. self.draw_selection_shape(curr_sel_obj)
  5963. # self.inform.emit('[selected] %s: %s selected' %
  5964. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5965. if curr_sel_obj.kind == 'gerber':
  5966. self.inform.emit(
  5967. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5968. color='green', name=str(curr_sel_obj.options['name'])))
  5969. elif curr_sel_obj.kind == 'excellon':
  5970. self.inform.emit(
  5971. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5972. color='brown', name=str(curr_sel_obj.options['name'])))
  5973. elif curr_sel_obj.kind == 'cncjob':
  5974. self.inform.emit(
  5975. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5976. color='blue', name=str(curr_sel_obj.options['name'])))
  5977. elif curr_sel_obj.kind == 'geometry':
  5978. self.inform.emit(
  5979. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5980. color='red', name=str(curr_sel_obj.options['name'])))
  5981. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5982. self.collection.set_all_inactive()
  5983. self.delete_selection_shape()
  5984. self.collection.set_active(objects_under_the_click_list[0])
  5985. # create the selection box around the selected object
  5986. curr_sel_obj = self.collection.get_active()
  5987. if self.defaults['global_selection_shape'] is True:
  5988. self.draw_selection_shape(curr_sel_obj)
  5989. # self.inform.emit('[selected] %s: %s selected' %
  5990. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5991. if curr_sel_obj.kind == 'gerber':
  5992. self.inform.emit(
  5993. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5994. color='green', name=str(curr_sel_obj.options['name'])))
  5995. elif curr_sel_obj.kind == 'excellon':
  5996. self.inform.emit(
  5997. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5998. color='brown', name=str(curr_sel_obj.options['name'])))
  5999. elif curr_sel_obj.kind == 'cncjob':
  6000. self.inform.emit(
  6001. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6002. color='blue', name=str(curr_sel_obj.options['name'])))
  6003. elif curr_sel_obj.kind == 'geometry':
  6004. self.inform.emit(
  6005. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6006. color='red', name=str(curr_sel_obj.options['name'])))
  6007. else:
  6008. self.collection.set_all_inactive()
  6009. self.delete_selection_shape()
  6010. if self.call_source == 'app':
  6011. # delete any text in the status bar, implicitly the last object name that was selected
  6012. self.inform.emit("")
  6013. else:
  6014. self.call_source = 'app'
  6015. else:
  6016. # If there is no selected object
  6017. # make active the first element of the overlapped objects list
  6018. if self.collection.get_active() is None:
  6019. self.collection.set_active(objects_under_the_click_list[0])
  6020. name_sel_obj = self.collection.get_active().options['name']
  6021. # In case that there is a selected object but it is not in the overlapped object list
  6022. # make that object inactive and activate the first element in the overlapped object list
  6023. if name_sel_obj not in objects_under_the_click_list:
  6024. self.collection.set_inactive(name_sel_obj)
  6025. name_sel_obj = objects_under_the_click_list[0]
  6026. self.collection.set_active(name_sel_obj)
  6027. else:
  6028. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6029. self.collection.set_all_inactive()
  6030. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6031. len(objects_under_the_click_list)])
  6032. curr_sel_obj = self.collection.get_active()
  6033. # delete the possible selection box around a possible selected object
  6034. self.delete_selection_shape()
  6035. # create the selection box around the selected object
  6036. if self.defaults['global_selection_shape'] is True:
  6037. self.draw_selection_shape(curr_sel_obj)
  6038. # self.inform.emit('[selected] %s: %s selected' %
  6039. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6040. if curr_sel_obj.kind == 'gerber':
  6041. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6042. color='green', name=str(curr_sel_obj.options['name'])))
  6043. elif curr_sel_obj.kind == 'excellon':
  6044. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6045. color='brown', name=str(curr_sel_obj.options['name'])))
  6046. elif curr_sel_obj.kind == 'cncjob':
  6047. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6048. color='blue', name=str(curr_sel_obj.options['name'])))
  6049. elif curr_sel_obj.kind == 'geometry':
  6050. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6051. color='red', name=str(curr_sel_obj.options['name'])))
  6052. # for obj in self.collection.get_list():
  6053. # obj.plot()
  6054. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6055. # TODO: on selected objects change the object colors and do not draw the selection box
  6056. # self.plotcanvas.update() # this updates the canvas
  6057. except Exception as e:
  6058. log.error("[ERROR] Something went bad. %s" % str(e))
  6059. return
  6060. def delete_hover_shape(self):
  6061. self.hover_shapes.clear()
  6062. self.hover_shapes.redraw()
  6063. def draw_hover_shape(self, sel_obj, color=None):
  6064. """
  6065. :param sel_obj: the object for which the hover shape must be drawn
  6066. :return:
  6067. """
  6068. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6069. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6070. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6071. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6072. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6073. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6074. hover_rect = hover_rect.buffer(-0.1)
  6075. hover_rect = hover_rect.buffer(0.2)
  6076. else:
  6077. hover_rect = hover_rect.buffer(-0.00393)
  6078. hover_rect = hover_rect.buffer(0.00787)
  6079. if color:
  6080. face = Color(color)
  6081. face.alpha = 0.2
  6082. outline = Color(color, alpha=0.8)
  6083. else:
  6084. face = Color(self.defaults['global_sel_fill'])
  6085. face.alpha = 0.2
  6086. outline = self.defaults['global_sel_line']
  6087. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6088. def delete_selection_shape(self):
  6089. self.move_tool.sel_shapes.clear()
  6090. self.move_tool.sel_shapes.redraw()
  6091. def draw_selection_shape(self, sel_obj, color=None):
  6092. """
  6093. :param sel_obj: the object for which the selection shape must be drawn
  6094. :return:
  6095. """
  6096. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6097. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6098. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6099. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6100. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6101. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6102. sel_rect = sel_rect.buffer(-0.1)
  6103. sel_rect = sel_rect.buffer(0.2)
  6104. else:
  6105. sel_rect = sel_rect.buffer(-0.00393)
  6106. sel_rect = sel_rect.buffer(0.00787)
  6107. if color:
  6108. face = Color(color, alpha=0.2)
  6109. outline = Color(color, alpha=0.8)
  6110. else:
  6111. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6112. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6113. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6114. color=outline,
  6115. face_color=face,
  6116. update=True,
  6117. layer=0,
  6118. tolerance=None))
  6119. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6120. """
  6121. :param old_coords: old coordinates
  6122. :param coords: new coordinates
  6123. :return:
  6124. """
  6125. if 'color' in kwargs:
  6126. color = kwargs['color']
  6127. else:
  6128. color = self.defaults['global_sel_line']
  6129. if 'face_color' in kwargs:
  6130. face_color = kwargs['face_color']
  6131. else:
  6132. face_color = self.defaults['global_sel_fill']
  6133. if 'face_alpha' in kwargs:
  6134. face_alpha = kwargs['face_alpha']
  6135. else:
  6136. face_alpha = 0.3
  6137. x0, y0 = old_coords
  6138. x1, y1 = coords
  6139. pt1 = (x0, y0)
  6140. pt2 = (x1, y0)
  6141. pt3 = (x1, y1)
  6142. pt4 = (x0, y1)
  6143. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6144. color_t = Color(face_color)
  6145. color_t.alpha = face_alpha
  6146. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6147. layer=0, tolerance=None)
  6148. def on_file_new_click(self):
  6149. if self.collection.get_list() and self.should_we_save:
  6150. msgbox = QtWidgets.QMessageBox()
  6151. # msgbox.setText("<B>Save changes ...</B>")
  6152. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6153. "Creating a New project will delete them.\n"
  6154. "Do you want to Save the project?"))
  6155. msgbox.setWindowTitle(_("Save changes"))
  6156. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6157. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6158. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6159. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6160. msgbox.setDefaultButton(bt_yes)
  6161. msgbox.exec_()
  6162. response = msgbox.clickedButton()
  6163. if response == bt_yes:
  6164. self.on_file_saveprojectas()
  6165. elif response == bt_cancel:
  6166. return
  6167. elif response == bt_no:
  6168. self.on_file_new()
  6169. else:
  6170. self.on_file_new()
  6171. self.inform.emit('[success] %s...' %
  6172. _("New Project created"))
  6173. def on_file_new(self):
  6174. """
  6175. Callback for menu item File->New. Returns the application to its
  6176. startup state. This method is thread-safe.
  6177. :return: None
  6178. """
  6179. self.report_usage("on_file_new")
  6180. # Remove everything from memory
  6181. App.log.debug("on_file_new()")
  6182. if self.call_source != 'app':
  6183. self.editor2object(cleanup=True)
  6184. # ## EDITOR section
  6185. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6186. self.exc_editor = FlatCAMExcEditor(self)
  6187. self.grb_editor = FlatCAMGrbEditor(self)
  6188. # Clear pool
  6189. self.clear_pool()
  6190. for obj in self.collection.get_list():
  6191. # delete shapes left drawn from mark shape_collections, if any
  6192. if isinstance(obj, FlatCAMGerber):
  6193. try:
  6194. obj.mark_shapes.enabled = False
  6195. obj.mark_shapes.clear(update=True)
  6196. except AttributeError:
  6197. pass
  6198. # also delete annotation shapes, if any
  6199. elif isinstance(obj, FlatCAMCNCjob):
  6200. try:
  6201. obj.annotation.enabled = False
  6202. obj.annotation.clear(update=True)
  6203. except AttributeError:
  6204. pass
  6205. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6206. self.init_tcl()
  6207. self.delete_selection_shape()
  6208. self.collection.delete_all()
  6209. self.setup_component_editor()
  6210. # Clear project filename
  6211. self.project_filename = None
  6212. # Load the application defaults
  6213. self.load_defaults(filename='current_defaults')
  6214. # Re-fresh project options
  6215. self.on_options_app2project()
  6216. # Init Tools
  6217. self.init_tools()
  6218. # Close any Tabs opened in the Plot Tab Area section
  6219. for index in range(self.ui.plot_tab_area.count()):
  6220. self.ui.plot_tab_area.closeTab(index)
  6221. # for whatever reason previous command does not close the last tab so I do it manually
  6222. self.ui.plot_tab_area.closeTab(0)
  6223. # # And then add again the Plot Area
  6224. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6225. self.ui.plot_tab_area.protectTab(0)
  6226. # take the focus of the Notebook on Project Tab.
  6227. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6228. self.set_ui_title(name=_("New Project - Not saved"))
  6229. def obj_properties(self):
  6230. self.report_usage("obj_properties()")
  6231. self.properties_tool.run(toggle=False)
  6232. def on_project_context_save(self):
  6233. obj = self.collection.get_active()
  6234. if type(obj) == FlatCAMGeometry:
  6235. self.on_file_exportdxf()
  6236. elif type(obj) == FlatCAMExcellon:
  6237. self.on_file_saveexcellon()
  6238. elif type(obj) == FlatCAMCNCjob:
  6239. obj.on_exportgcode_button_click()
  6240. elif type(obj) == FlatCAMGerber:
  6241. self.on_file_savegerber()
  6242. def obj_move(self):
  6243. self.report_usage("obj_move()")
  6244. self.move_tool.run(toggle=False)
  6245. def on_fileopengerber(self, checked=None, name=None):
  6246. """
  6247. File menu callback for opening a Gerber.
  6248. :return: None
  6249. """
  6250. self.report_usage("on_fileopengerber")
  6251. App.log.debug("on_fileopengerber()")
  6252. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6253. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6254. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6255. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6256. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6257. "*.mil);;" \
  6258. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6259. "Allegro Files (*.art);;" \
  6260. "Mentor Files (*.pho *.gdo);;" \
  6261. "All Files (*.*)"
  6262. if name is None:
  6263. try:
  6264. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6265. directory=self.get_last_folder(),
  6266. filter=_filter_)
  6267. except TypeError:
  6268. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6269. filenames = [str(filename) for filename in filenames]
  6270. else:
  6271. filenames = [name]
  6272. if len(filenames) == 0:
  6273. self.inform.emit('[WARNING_NOTCL] %s' %
  6274. _("Open Gerber cancelled."))
  6275. else:
  6276. for filename in filenames:
  6277. if filename != '':
  6278. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6279. def on_fileopenexcellon(self, checked=None, name=None):
  6280. """
  6281. File menu callback for opening an Excellon file.
  6282. :return: None
  6283. """
  6284. self.report_usage("on_fileopenexcellon")
  6285. App.log.debug("on_fileopenexcellon()")
  6286. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6287. "All Files (*.*)"
  6288. if name is None:
  6289. try:
  6290. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6291. directory=self.get_last_folder(),
  6292. filter=_filter_)
  6293. except TypeError:
  6294. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6295. filenames = [str(filename) for filename in filenames]
  6296. else:
  6297. filenames = [str(name)]
  6298. if len(filenames) == 0:
  6299. self.inform.emit('[WARNING_NOTCL]%s' %
  6300. _(" Open Excellon cancelled."))
  6301. else:
  6302. for filename in filenames:
  6303. if filename != '':
  6304. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6305. def on_fileopengcode(self, checked=None, name=None):
  6306. """
  6307. File menu call back for opening gcode.
  6308. :return: None
  6309. """
  6310. self.report_usage("on_fileopengcode")
  6311. App.log.debug("on_fileopengcode()")
  6312. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6313. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6314. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6315. "All Files (*.*)"
  6316. if name is None:
  6317. try:
  6318. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6319. directory=self.get_last_folder(),
  6320. filter=_filter_)
  6321. except TypeError:
  6322. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6323. filenames = [str(filename) for filename in filenames]
  6324. else:
  6325. filenames = [name]
  6326. if len(filenames) == 0:
  6327. self.inform.emit('[WARNING_NOTCL] %s' %
  6328. _("Open G-Code cancelled."))
  6329. else:
  6330. for filename in filenames:
  6331. if filename != '':
  6332. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6333. def on_file_openproject(self, checked=None):
  6334. """
  6335. File menu callback for opening a project.
  6336. :return: None
  6337. """
  6338. self.report_usage("on_file_openproject")
  6339. App.log.debug("on_file_openproject()")
  6340. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6341. try:
  6342. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6343. directory=self.get_last_folder(), filter=_filter_)
  6344. except TypeError:
  6345. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6346. # The Qt methods above will return a QString which can cause problems later.
  6347. # So far json.dump() will fail to serialize it.
  6348. # TODO: Improve the serialization methods and remove this fix.
  6349. filename = str(filename)
  6350. if filename == "":
  6351. self.inform.emit('[WARNING_NOTCL] %s' %
  6352. _("Open Project cancelled."))
  6353. else:
  6354. # self.worker_task.emit({'fcn': self.open_project,
  6355. # 'params': [filename]})
  6356. # The above was failing because open_project() is not
  6357. # thread safe. The new_project()
  6358. self.open_project(filename)
  6359. def on_file_openconfig(self, checked=None):
  6360. """
  6361. File menu callback for opening a config file.
  6362. :return: None
  6363. """
  6364. self.report_usage("on_file_openconfig")
  6365. App.log.debug("on_file_openconfig()")
  6366. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6367. try:
  6368. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6369. directory=self.data_path, filter=_filter_)
  6370. except TypeError:
  6371. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6372. filter=_filter_)
  6373. if filename == "":
  6374. self.inform.emit('[WARNING_NOTCL] %s' %
  6375. _("Open Config cancelled."))
  6376. else:
  6377. self.open_config_file(filename)
  6378. def on_file_exportsvg(self):
  6379. """
  6380. Callback for menu item File->Export SVG.
  6381. :return: None
  6382. """
  6383. self.report_usage("on_file_exportsvg")
  6384. App.log.debug("on_file_exportsvg()")
  6385. obj = self.collection.get_active()
  6386. if obj is None:
  6387. self.inform.emit('[WARNING_NOTCL] %s' %
  6388. _("No object selected."))
  6389. msg = _("Please Select a Geometry object to export")
  6390. msgbox = QtWidgets.QMessageBox()
  6391. msgbox.setInformativeText(msg)
  6392. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6393. msgbox.setDefaultButton(bt_ok)
  6394. msgbox.exec_()
  6395. return
  6396. # Check for more compatible types and add as required
  6397. if (not isinstance(obj, FlatCAMGeometry)
  6398. and not isinstance(obj, FlatCAMGerber)
  6399. and not isinstance(obj, FlatCAMCNCjob)
  6400. and not isinstance(obj, FlatCAMExcellon)):
  6401. msg = '[ERROR_NOTCL] %s' % \
  6402. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6403. msgbox = QtWidgets.QMessageBox()
  6404. msgbox.setInformativeText(msg)
  6405. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6406. msgbox.setDefaultButton(bt_ok)
  6407. msgbox.exec_()
  6408. return
  6409. name = obj.options["name"]
  6410. _filter = "SVG File (*.svg);;All Files (*.*)"
  6411. try:
  6412. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6413. caption=_("Export SVG"),
  6414. directory=self.get_last_save_folder() + '/' + str(name),
  6415. filter=_filter)
  6416. except TypeError:
  6417. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6418. filename = str(filename)
  6419. if filename == "":
  6420. self.inform.emit('[WARNING_NOTCL]%s' %
  6421. _(" Export SVG cancelled."))
  6422. return
  6423. else:
  6424. self.export_svg(name, filename)
  6425. if self.defaults["global_open_style"] is False:
  6426. self.file_opened.emit("SVG", filename)
  6427. self.file_saved.emit("SVG", filename)
  6428. def on_file_exportpng(self):
  6429. self.report_usage("on_file_exportpng")
  6430. App.log.debug("on_file_exportpng()")
  6431. self.date = str(datetime.today()).rpartition('.')[0]
  6432. self.date = ''.join(c for c in self.date if c not in ':-')
  6433. self.date = self.date.replace(' ', '_')
  6434. image = _screenshot()
  6435. data = np.asarray(image)
  6436. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6437. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6438. _('Data must be a 3D array with last dimension 3 or 4'))
  6439. return
  6440. filter_ = "PNG File (*.png);;All Files (*.*)"
  6441. try:
  6442. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6443. caption=_("Export PNG Image"),
  6444. directory=self.get_last_save_folder() + '/png_' + self.date,
  6445. filter=filter_)
  6446. except TypeError:
  6447. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6448. filename = str(filename)
  6449. if filename == "":
  6450. self.inform.emit(_("Export PNG cancelled."))
  6451. return
  6452. else:
  6453. write_png(filename, data)
  6454. if self.defaults["global_open_style"] is False:
  6455. self.file_opened.emit("png", filename)
  6456. self.file_saved.emit("png", filename)
  6457. def on_file_savegerber(self):
  6458. """
  6459. Callback for menu item in Project context menu.
  6460. :return: None
  6461. """
  6462. self.report_usage("on_file_savegerber")
  6463. App.log.debug("on_file_savegerber()")
  6464. obj = self.collection.get_active()
  6465. if obj is None:
  6466. self.inform.emit('[WARNING_NOTCL] %s' %
  6467. _("No object selected. Please select an Gerber object to export."))
  6468. return
  6469. # Check for more compatible types and add as required
  6470. if not isinstance(obj, FlatCAMGerber):
  6471. self.inform.emit('[ERROR_NOTCL] %s' %
  6472. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6473. return
  6474. name = self.collection.get_active().options["name"]
  6475. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6476. try:
  6477. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6478. caption="Save Gerber source file",
  6479. directory=self.get_last_save_folder() + '/' + name,
  6480. filter=_filter)
  6481. except TypeError:
  6482. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6483. filename = str(filename)
  6484. if filename == "":
  6485. self.inform.emit('[WARNING_NOTCL] %s' %
  6486. _("Save Gerber source file cancelled."))
  6487. return
  6488. else:
  6489. self.save_source_file(name, filename)
  6490. if self.defaults["global_open_style"] is False:
  6491. self.file_opened.emit("Gerber", filename)
  6492. self.file_saved.emit("Gerber", filename)
  6493. def on_file_saveexcellon(self):
  6494. """
  6495. Callback for menu item in project context menu.
  6496. :return: None
  6497. """
  6498. self.report_usage("on_file_saveexcellon")
  6499. App.log.debug("on_file_saveexcellon()")
  6500. obj = self.collection.get_active()
  6501. if obj is None:
  6502. self.inform.emit('[WARNING_NOTCL] %s' %
  6503. _("No object selected. Please select an Excellon object to export."))
  6504. return
  6505. # Check for more compatible types and add as required
  6506. if not isinstance(obj, FlatCAMExcellon):
  6507. self.inform.emit('[ERROR_NOTCL] %s' %
  6508. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6509. return
  6510. name = self.collection.get_active().options["name"]
  6511. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6512. try:
  6513. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6514. caption=_("Save Excellon source file"),
  6515. directory=self.get_last_save_folder() + '/' + name,
  6516. filter=_filter)
  6517. except TypeError:
  6518. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6519. filename = str(filename)
  6520. if filename == "":
  6521. self.inform.emit('[WARNING_NOTCL] %s' %
  6522. _("Saving Excellon source file cancelled."))
  6523. return
  6524. else:
  6525. self.save_source_file(name, filename)
  6526. if self.defaults["global_open_style"] is False:
  6527. self.file_opened.emit("Excellon", filename)
  6528. self.file_saved.emit("Excellon", filename)
  6529. def on_file_exportexcellon(self):
  6530. """
  6531. Callback for menu item File->Export->Excellon.
  6532. :return: None
  6533. """
  6534. self.report_usage("on_file_exportexcellon")
  6535. App.log.debug("on_file_exportexcellon()")
  6536. obj = self.collection.get_active()
  6537. if obj is None:
  6538. self.inform.emit('[WARNING_NOTCL] %s' %
  6539. _("No object selected. Please Select an Excellon object to export."))
  6540. return
  6541. # Check for more compatible types and add as required
  6542. if not isinstance(obj, FlatCAMExcellon):
  6543. self.inform.emit('[ERROR_NOTCL] %s' %
  6544. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6545. return
  6546. name = self.collection.get_active().options["name"]
  6547. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6548. try:
  6549. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6550. caption=_("Export Excellon"),
  6551. directory=self.get_last_save_folder() + '/' + name,
  6552. filter=_filter)
  6553. except TypeError:
  6554. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6555. filename = str(filename)
  6556. if filename == "":
  6557. self.inform.emit('[WARNING_NOTCL] %s' %
  6558. _("Export Excellon cancelled."))
  6559. return
  6560. else:
  6561. self.export_excellon(name, filename)
  6562. if self.defaults["global_open_style"] is False:
  6563. self.file_opened.emit("Excellon", filename)
  6564. self.file_saved.emit("Excellon", filename)
  6565. def on_file_exportgerber(self):
  6566. """
  6567. Callback for menu item File->Export->Gerber.
  6568. :return: None
  6569. """
  6570. self.report_usage("on_file_exportgerber")
  6571. App.log.debug("on_file_exportgerber()")
  6572. obj = self.collection.get_active()
  6573. if obj is None:
  6574. self.inform.emit('[WARNING_NOTCL] %s' %
  6575. _("No object selected. Please Select an Gerber object to export."))
  6576. return
  6577. # Check for more compatible types and add as required
  6578. if not isinstance(obj, FlatCAMGerber):
  6579. self.inform.emit('[ERROR_NOTCL] %s' %
  6580. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6581. return
  6582. name = self.collection.get_active().options["name"]
  6583. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6584. try:
  6585. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6586. caption=_("Export Gerber"),
  6587. directory=self.get_last_save_folder() + '/' + name,
  6588. filter=_filter_)
  6589. except TypeError:
  6590. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6591. filename = str(filename)
  6592. if filename == "":
  6593. self.inform.emit('[WARNING_NOTCL] %s' %
  6594. _("Export Gerber cancelled."))
  6595. return
  6596. else:
  6597. self.export_gerber(name, filename)
  6598. if self.defaults["global_open_style"] is False:
  6599. self.file_opened.emit("Gerber", filename)
  6600. self.file_saved.emit("Gerber", filename)
  6601. def on_file_exportdxf(self):
  6602. """
  6603. Callback for menu item File->Export DXF.
  6604. :return: None
  6605. """
  6606. self.report_usage("on_file_exportdxf")
  6607. App.log.debug("on_file_exportdxf()")
  6608. obj = self.collection.get_active()
  6609. if obj is None:
  6610. self.inform.emit('[WARNING_NOTCL] %s' %
  6611. _("No object selected."))
  6612. msg = _("Please Select a Geometry object to export")
  6613. msgbox = QtWidgets.QMessageBox()
  6614. msgbox.setInformativeText(msg)
  6615. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6616. msgbox.setDefaultButton(bt_ok)
  6617. msgbox.exec_()
  6618. return
  6619. # Check for more compatible types and add as required
  6620. if not isinstance(obj, FlatCAMGeometry):
  6621. msg = '[ERROR_NOTCL] %s' % \
  6622. _("Only Geometry objects can be used.")
  6623. msgbox = QtWidgets.QMessageBox()
  6624. msgbox.setInformativeText(msg)
  6625. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6626. msgbox.setDefaultButton(bt_ok)
  6627. msgbox.exec_()
  6628. return
  6629. name = self.collection.get_active().options["name"]
  6630. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6631. try:
  6632. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6633. caption=_("Export DXF"),
  6634. directory=self.get_last_save_folder() + '/' + name,
  6635. filter=_filter_)
  6636. except TypeError:
  6637. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6638. filter=_filter_)
  6639. filename = str(filename)
  6640. if filename == "":
  6641. self.inform.emit('[WARNING_NOTCL] %s' %
  6642. _("Export DXF cancelled."))
  6643. return
  6644. else:
  6645. self.export_dxf(name, filename)
  6646. if self.defaults["global_open_style"] is False:
  6647. self.file_opened.emit("DXF", filename)
  6648. self.file_saved.emit("DXF", filename)
  6649. def on_file_importsvg(self, type_of_obj):
  6650. """
  6651. Callback for menu item File->Import SVG.
  6652. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6653. :type type_of_obj: str
  6654. :return: None
  6655. """
  6656. self.report_usage("on_file_importsvg")
  6657. App.log.debug("on_file_importsvg()")
  6658. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6659. try:
  6660. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6661. directory=self.get_last_folder(), filter=_filter_)
  6662. except TypeError:
  6663. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6664. filter=_filter_)
  6665. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6666. type_of_obj = "geometry"
  6667. filenames = [str(filename) for filename in filenames]
  6668. if len(filenames) == 0:
  6669. self.inform.emit('[WARNING_NOTCL] %s' %
  6670. _("Open SVG cancelled."))
  6671. else:
  6672. for filename in filenames:
  6673. if filename != '':
  6674. self.worker_task.emit({'fcn': self.import_svg,
  6675. 'params': [filename, type_of_obj]})
  6676. def on_file_importdxf(self, type_of_obj):
  6677. """
  6678. Callback for menu item File->Import DXF.
  6679. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6680. :type type_of_obj: str
  6681. :return: None
  6682. """
  6683. self.report_usage("on_file_importdxf")
  6684. App.log.debug("on_file_importdxf()")
  6685. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6686. try:
  6687. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6688. directory=self.get_last_folder(),
  6689. filter=_filter_)
  6690. except TypeError:
  6691. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6692. filter=_filter_)
  6693. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6694. type_of_obj = "geometry"
  6695. filenames = [str(filename) for filename in filenames]
  6696. if len(filenames) == 0:
  6697. self.inform.emit('[WARNING_NOTCL] %s' %
  6698. _("Open DXF cancelled."))
  6699. else:
  6700. for filename in filenames:
  6701. if filename != '':
  6702. self.worker_task.emit({'fcn': self.import_dxf,
  6703. 'params': [filename, type_of_obj]})
  6704. # ###############################################################################################################
  6705. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6706. # ###############################################################################################################
  6707. def init_code_editor(self, name):
  6708. # Signals section
  6709. # Disconnect the old signals
  6710. try:
  6711. self.ui.buttonOpen.clicked.disconnect()
  6712. except TypeError:
  6713. pass
  6714. try:
  6715. self.ui.buttonSave.clicked.disconnect()
  6716. except TypeError:
  6717. pass
  6718. # add the tab if it was closed
  6719. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  6720. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6721. # delete the absolute and relative position and messages in the infobar
  6722. self.ui.position_label.setText("")
  6723. self.ui.rel_position_label.setText("")
  6724. # first clear previous text in text editor (if any)
  6725. self.ui.code_editor.clear()
  6726. self.ui.code_editor.setReadOnly(False)
  6727. self.toggle_codeeditor = True
  6728. self.ui.code_editor.completer_enable = False
  6729. self.ui.buttonRun.hide()
  6730. # Switch plot_area to CNCJob tab
  6731. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6732. def on_view_source(self):
  6733. self.inform.emit('%s' %
  6734. _("Viewing the source code of the selected object."))
  6735. self.proc_container.view.set_busy(_("Loading..."))
  6736. try:
  6737. obj = self.collection.get_active()
  6738. except Exception as e:
  6739. log.debug("App.on_view_source() --> %s" % str(e))
  6740. self.inform.emit('[WARNING_NOTCL] %s' %
  6741. _("Select an Gerber or Excellon file to view it's source file."))
  6742. return 'fail'
  6743. if obj.kind == 'gerber':
  6744. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6745. else:
  6746. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6747. self.init_code_editor(name=_("Source Editor"))
  6748. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6749. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6750. # then append the text from GCode to the text editor
  6751. try:
  6752. file = StringIO(obj.source_file)
  6753. except AttributeError:
  6754. self.inform.emit('[WARNING_NOTCL] %s' %
  6755. _("There is no selected object for which to see it's source file code."))
  6756. return 'fail'
  6757. self.ui.cncjob_frame.hide()
  6758. try:
  6759. for line in file:
  6760. QtWidgets.QApplication.processEvents()
  6761. proc_line = str(line).strip('\n')
  6762. self.ui.code_editor.append(proc_line)
  6763. except Exception as e:
  6764. log.debug('App.on_view_source() -->%s' % str(e))
  6765. self.inform.emit('[ERROR] %s: %s' %
  6766. (_('Failed to load the source code for the selected object'), str(e)))
  6767. return
  6768. self.handleTextChanged()
  6769. self.ui.cncjob_frame.show()
  6770. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6771. self.proc_container.view.set_idle()
  6772. # self.ui.show()
  6773. def on_toggle_code_editor(self):
  6774. self.report_usage("on_toggle_code_editor()")
  6775. if self.toggle_codeeditor is False:
  6776. self.init_code_editor(name=_("Code Editor"))
  6777. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6778. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6779. else:
  6780. for idx in range(self.ui.plot_tab_area.count()):
  6781. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6782. self.ui.plot_tab_area.closeTab(idx)
  6783. break
  6784. self.toggle_codeeditor = False
  6785. def on_filenewscript(self):
  6786. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6787. self.init_code_editor(name=_("Script Editor"))
  6788. self.ui.code_editor.completer_enable = True
  6789. self.ui.code_editor.append(_(
  6790. "#\n"
  6791. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6792. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6793. "#\n\n"
  6794. "# FlatCAM commands list:\n"
  6795. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  6796. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  6797. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  6798. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  6799. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  6800. "# SubtractRectangle, Version, WriteGCode\n"
  6801. "#\n\n"
  6802. ))
  6803. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6804. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6805. self.ui.buttonRun.show()
  6806. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  6807. self.handleTextChanged()
  6808. self.ui.code_editor.show()
  6809. def on_fileopenscript(self):
  6810. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6811. try:
  6812. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6813. directory=self.get_last_folder(), filter=_filter_)
  6814. except TypeError:
  6815. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6816. # The Qt methods above will return a QString which can cause problems later.
  6817. # So far json.dump() will fail to serialize it.
  6818. # TODO: Improve the serialization methods and remove this fix.
  6819. filename = str(filename)
  6820. if filename == "":
  6821. self.inform.emit('[WARNING_NOTCL] %s' %
  6822. _("Open TCL script cancelled."))
  6823. else:
  6824. self.on_filenewscript()
  6825. try:
  6826. with open(filename, "r") as opened_script:
  6827. try:
  6828. for line in opened_script:
  6829. proc_line = str(line).strip('\n')
  6830. self.ui.code_editor.append(proc_line)
  6831. except Exception as e:
  6832. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6833. self.inform.emit('[ERROR] %s %s' %
  6834. (_('App.on_fileopenscript() -->'), str(e)))
  6835. return
  6836. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6837. self.handleTextChanged()
  6838. self.ui.show()
  6839. except Exception as e:
  6840. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6841. def on_filerunscript(self, name=None):
  6842. """
  6843. File menu callback for loading and running a TCL script.
  6844. :return: None
  6845. """
  6846. self.report_usage("on_filerunscript")
  6847. App.log.debug("on_file_runscript()")
  6848. if name:
  6849. filename = name
  6850. else:
  6851. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6852. try:
  6853. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6854. directory=self.get_last_folder(), filter=_filter_)
  6855. except TypeError:
  6856. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6857. # The Qt methods above will return a QString which can cause problems later.
  6858. # So far json.dump() will fail to serialize it.
  6859. # TODO: Improve the serialization methods and remove this fix.
  6860. filename = str(filename)
  6861. if filename == "":
  6862. self.inform.emit('[WARNING_NOTCL] %s' %
  6863. _("Run TCL script cancelled."))
  6864. else:
  6865. try:
  6866. with open(filename, "r") as tcl_script:
  6867. cmd_line_shellfile_content = tcl_script.read()
  6868. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6869. except Exception as e:
  6870. log.debug("App.on_filerunscript() -> %s" % str(e))
  6871. sys.exit(2)
  6872. def on_file_saveproject(self):
  6873. """
  6874. Callback for menu item File->Save Project. Saves the project to
  6875. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6876. if set to None. The project is saved by calling ``self.save_project()``.
  6877. :return: None
  6878. """
  6879. self.report_usage("on_file_saveproject")
  6880. if self.project_filename is None:
  6881. self.on_file_saveprojectas()
  6882. else:
  6883. self.worker_task.emit({'fcn': self.save_project,
  6884. 'params': [self.project_filename]})
  6885. if self.defaults["global_open_style"] is False:
  6886. self.file_opened.emit("project", self.project_filename)
  6887. self.file_saved.emit("project", self.project_filename)
  6888. self.set_ui_title(name=self.project_filename)
  6889. self.should_we_save = False
  6890. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6891. """
  6892. Callback for menu item File->Save Project As... Opens a file
  6893. chooser and saves the project to the given file via
  6894. ``self.save_project()``.
  6895. :param make_copy if to be create a copy of the project; boolean
  6896. :param use_thread: if to be run in a separate thread; boolean
  6897. :param quit_action: if to be followed by quiting the application; boolean
  6898. :return: None
  6899. """
  6900. self.report_usage("on_file_saveprojectas")
  6901. self.date = str(datetime.today()).rpartition('.')[0]
  6902. self.date = ''.join(c for c in self.date if c not in ':-')
  6903. self.date = self.date.replace(' ', '_')
  6904. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6905. try:
  6906. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6907. caption=_("Save Project As ..."),
  6908. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6909. filter=filter_)
  6910. except TypeError:
  6911. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6912. filename = str(filename)
  6913. if filename == '':
  6914. self.inform.emit('[WARNING_NOTCL] %s' %
  6915. _("Save Project cancelled."))
  6916. return
  6917. try:
  6918. f = open(filename, 'r')
  6919. f.close()
  6920. except IOError:
  6921. pass
  6922. if use_thread is True:
  6923. self.worker_task.emit({'fcn': self.save_project,
  6924. 'params': [filename, quit_action]})
  6925. else:
  6926. self.save_project(filename, quit_action)
  6927. # self.save_project(filename)
  6928. if self.defaults["global_open_style"] is False:
  6929. self.file_opened.emit("project", filename)
  6930. self.file_saved.emit("project", filename)
  6931. if not make_copy:
  6932. self.project_filename = filename
  6933. self.set_ui_title(name=self.project_filename)
  6934. self.should_we_save = False
  6935. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6936. """
  6937. Exports a Geometry Object to an SVG file.
  6938. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6939. :param filename: Path to the SVG file to save to.
  6940. :param scale_factor: factor by which to change/scale the thickness of the features
  6941. :return:
  6942. """
  6943. self.report_usage("export_svg()")
  6944. if filename is None:
  6945. filename = self.defaults["global_last_save_folder"]
  6946. self.log.debug("export_svg()")
  6947. try:
  6948. obj = self.collection.get_by_name(str(obj_name))
  6949. except:
  6950. # TODO: The return behavior has not been established... should raise exception?
  6951. return "Could not retrieve object: %s" % obj_name
  6952. with self.proc_container.new(_("Exporting SVG")) as proc:
  6953. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6954. # Determine bounding area for svg export
  6955. bounds = obj.bounds()
  6956. size = obj.size()
  6957. # Convert everything to strings for use in the xml doc
  6958. svgwidth = str(size[0])
  6959. svgheight = str(size[1])
  6960. minx = str(bounds[0])
  6961. miny = str(bounds[1] - size[1])
  6962. uom = obj.units.lower()
  6963. # Add a SVG Header and footer to the svg output from shapely
  6964. # The transform flips the Y Axis so that everything renders
  6965. # properly within svg apps such as inkscape
  6966. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6967. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6968. svg_header += 'width="' + svgwidth + uom + '" '
  6969. svg_header += 'height="' + svgheight + uom + '" '
  6970. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6971. svg_header += '<g transform="scale(1,-1)">'
  6972. svg_footer = '</g> </svg>'
  6973. svg_elem = svg_header + exported_svg + svg_footer
  6974. # Parse the xml through a xml parser just to add line feeds
  6975. # and to make it look more pretty for the output
  6976. svgcode = parse_xml_string(svg_elem)
  6977. try:
  6978. with open(filename, 'w') as fp:
  6979. fp.write(svgcode.toprettyxml())
  6980. except PermissionError:
  6981. self.inform.emit('[WARNING] %s' %
  6982. _("Permission denied, saving not possible.\n"
  6983. "Most likely another app is holding the file open and not accessible."))
  6984. return 'fail'
  6985. if self.defaults["global_open_style"] is False:
  6986. self.file_opened.emit("SVG", filename)
  6987. self.file_saved.emit("SVG", filename)
  6988. self.inform.emit('[success] %s: %s' %
  6989. (_("SVG file exported to"), filename))
  6990. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6991. """
  6992. Exports a Geometry Object to an SVG file in negative.
  6993. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6994. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6995. :param filename: Path to the SVG file to save to.
  6996. :param boundary: thickness of a black border to surround all the features
  6997. :param scale_factor: factor by which to change/scale the thickness of the features
  6998. :param use_thread: if to be run in a separate thread; boolean
  6999. :return:
  7000. """
  7001. self.report_usage("export_negative()")
  7002. if filename is None:
  7003. filename = self.defaults["global_last_save_folder"]
  7004. self.log.debug("export_svg() negative")
  7005. try:
  7006. obj = self.collection.get_by_name(str(obj_name))
  7007. except:
  7008. # TODO: The return behavior has not been established... should raise exception?
  7009. return "Could not retrieve object: %s" % obj_name
  7010. try:
  7011. box = self.collection.get_by_name(str(box_name))
  7012. except:
  7013. # TODO: The return behavior has not been established... should raise exception?
  7014. return "Could not retrieve object: %s" % box_name
  7015. if box is None:
  7016. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7017. (_("No object Box. Using instead"), obj))
  7018. box = obj
  7019. def make_negative_film():
  7020. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7021. self.progress.emit(40)
  7022. # Determine bounding area for svg export
  7023. bounds = box.bounds()
  7024. size = box.size()
  7025. uom = obj.units.lower()
  7026. # Convert everything to strings for use in the xml doc
  7027. svgwidth = str(size[0] + (2 * boundary))
  7028. svgheight = str(size[1] + (2 * boundary))
  7029. minx = str(bounds[0] - boundary)
  7030. miny = str(bounds[1] + boundary + size[1])
  7031. miny_rect = str(bounds[1] - boundary)
  7032. # Add a SVG Header and footer to the svg output from shapely
  7033. # The transform flips the Y Axis so that everything renders
  7034. # properly within svg apps such as inkscape
  7035. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7036. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7037. svg_header += 'width="' + svgwidth + uom + '" '
  7038. svg_header += 'height="' + svgheight + uom + '" '
  7039. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7040. svg_header += '>'
  7041. svg_header += '<g transform="scale(1,-1)">'
  7042. svg_footer = '</g> </svg>'
  7043. self.progress.emit(60)
  7044. # Change the attributes of the exported SVG
  7045. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7046. # We set opacity to maximum
  7047. # We set the color to WHITE
  7048. root = ET.fromstring(exported_svg)
  7049. for child in root:
  7050. child.set('fill', '#FFFFFF')
  7051. child.set('opacity', '1.0')
  7052. child.set('stroke', '#FFFFFF')
  7053. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7054. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7055. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7056. first_svg_elem_tag = 'rect'
  7057. first_svg_elem_attribs = {
  7058. 'x': minx,
  7059. 'y': miny_rect,
  7060. 'width': svgwidth,
  7061. 'height': svgheight,
  7062. 'id': 'neg_rect',
  7063. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7064. }
  7065. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7066. exported_svg = ET.tostring(root)
  7067. svg_elem = svg_header + str(exported_svg) + svg_footer
  7068. self.progress.emit(80)
  7069. # Parse the xml through a xml parser just to add line feeds
  7070. # and to make it look more pretty for the output
  7071. doc = parse_xml_string(svg_elem)
  7072. try:
  7073. with open(filename, 'w') as fp:
  7074. fp.write(doc.toprettyxml())
  7075. except PermissionError:
  7076. self.inform.emit('[WARNING] %s' %
  7077. _("Permission denied, saving not possible.\n"
  7078. "Most likely another app is holding the file open and not accessible."))
  7079. return 'fail'
  7080. self.progress.emit(100)
  7081. if self.defaults["global_open_style"] is False:
  7082. self.file_opened.emit("SVG", filename)
  7083. self.file_saved.emit("SVG", filename)
  7084. self.inform.emit('[success] %s: %s' %
  7085. (_("SVG file exported to"), filename))
  7086. if use_thread is True:
  7087. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7088. def job_thread_film(app_obj):
  7089. try:
  7090. make_negative_film()
  7091. except Exception as e:
  7092. proc.done()
  7093. return
  7094. proc.done()
  7095. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7096. else:
  7097. make_negative_film()
  7098. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7099. """
  7100. Exports a Geometry Object to an SVG file in positive black.
  7101. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7102. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7103. :param filename: Path to the SVG file to save to.
  7104. :param scale_factor: factor by which to change/scale the thickness of the features
  7105. :param use_thread: if to be run in a separate thread; boolean
  7106. :return:
  7107. """
  7108. self.report_usage("export_svg_black()")
  7109. if filename is None:
  7110. filename = self.defaults["global_last_save_folder"]
  7111. self.log.debug("export_svg() black")
  7112. try:
  7113. obj = self.collection.get_by_name(str(obj_name))
  7114. except:
  7115. # TODO: The return behavior has not been established... should raise exception?
  7116. return "Could not retrieve object: %s" % obj_name
  7117. try:
  7118. box = self.collection.get_by_name(str(box_name))
  7119. except:
  7120. # TODO: The return behavior has not been established... should raise exception?
  7121. return "Could not retrieve object: %s" % box_name
  7122. if box is None:
  7123. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7124. (_("No object Box. Using instead"), obj))
  7125. box = obj
  7126. def make_black_film():
  7127. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7128. self.progress.emit(40)
  7129. # Change the attributes of the exported SVG
  7130. # We don't need stroke-width
  7131. # We set opacity to maximum
  7132. # We set the colour to WHITE
  7133. root = ET.fromstring(exported_svg)
  7134. for child in root:
  7135. child.set('fill', '#000000')
  7136. child.set('opacity', '1.0')
  7137. child.set('stroke', '#000000')
  7138. exported_svg = ET.tostring(root)
  7139. # Determine bounding area for svg export
  7140. bounds = box.bounds()
  7141. size = box.size()
  7142. # This contain the measure units
  7143. uom = obj.units.lower()
  7144. # Define a boundary around SVG of about 1.0mm (~39mils)
  7145. if uom in "mm":
  7146. boundary = 1.0
  7147. else:
  7148. boundary = 0.0393701
  7149. self.progress.emit(80)
  7150. # Convert everything to strings for use in the xml doc
  7151. svgwidth = str(size[0] + (2 * boundary))
  7152. svgheight = str(size[1] + (2 * boundary))
  7153. minx = str(bounds[0] - boundary)
  7154. miny = str(bounds[1] + boundary + size[1])
  7155. self.log.debug(minx)
  7156. self.log.debug(miny)
  7157. # Add a SVG Header and footer to the svg output from shapely
  7158. # The transform flips the Y Axis so that everything renders
  7159. # properly within svg apps such as inkscape
  7160. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7161. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7162. svg_header += 'width="' + svgwidth + uom + '" '
  7163. svg_header += 'height="' + svgheight + uom + '" '
  7164. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7165. svg_header += '>'
  7166. svg_header += '<g transform="scale(1,-1)">'
  7167. svg_footer = '</g> </svg>'
  7168. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7169. self.progress.emit(90)
  7170. # Parse the xml through a xml parser just to add line feeds
  7171. # and to make it look more pretty for the output
  7172. doc = parse_xml_string(svg_elem)
  7173. try:
  7174. with open(filename, 'w') as fp:
  7175. fp.write(doc.toprettyxml())
  7176. except PermissionError:
  7177. self.inform.emit('[WARNING] %s' %
  7178. _("Permission denied, saving not possible.\n"
  7179. "Most likely another app is holding the file open and not accessible."))
  7180. return 'fail'
  7181. self.progress.emit(100)
  7182. if self.defaults["global_open_style"] is False:
  7183. self.file_opened.emit("SVG", filename)
  7184. self.file_saved.emit("SVG", filename)
  7185. self.inform.emit('[success] %s: %s' %
  7186. (_("SVG file exported to"), filename))
  7187. if use_thread is True:
  7188. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7189. def job_thread_film(app_obj):
  7190. try:
  7191. make_black_film()
  7192. except Exception as e:
  7193. proc.done()
  7194. return
  7195. proc.done()
  7196. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7197. else:
  7198. make_black_film()
  7199. def save_source_file(self, obj_name, filename, use_thread=True):
  7200. """
  7201. Exports a FlatCAM Object to an Gerber/Excellon file.
  7202. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7203. :param filename: Path to the Gerber file to save to.
  7204. :param use_thread: if to be run in a separate thread
  7205. :return:
  7206. """
  7207. self.report_usage("save source file()")
  7208. if filename is None:
  7209. filename = self.defaults["global_last_save_folder"]
  7210. self.log.debug("save source file()")
  7211. obj = self.collection.get_by_name(obj_name)
  7212. file_string = StringIO(obj.source_file)
  7213. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7214. try:
  7215. with open(filename, 'w') as file:
  7216. file.writelines('G04*\n')
  7217. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7218. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7219. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7220. file.writelines('G04 Created on : %s*\n' % time_string)
  7221. for line in file_string:
  7222. file.writelines(line)
  7223. except PermissionError:
  7224. self.inform.emit('[WARNING] %s' %
  7225. _("Permission denied, saving not possible.\n"
  7226. "Most likely another app is holding the file open and not accessible."))
  7227. return 'fail'
  7228. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7229. """
  7230. Exports a Excellon Object to an Excellon file.
  7231. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7232. :param filename: Path to the Excellon file to save to.
  7233. :param use_thread: if to be run in a separate thread
  7234. :return:
  7235. """
  7236. self.report_usage("export_excellon()")
  7237. if filename is None:
  7238. filename = self.defaults["global_last_save_folder"]
  7239. self.log.debug("export_excellon()")
  7240. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7241. self.defaults["excellon_exp_decimals"]
  7242. )
  7243. units = ''
  7244. if local_use is None:
  7245. try:
  7246. obj = self.collection.get_by_name(str(obj_name))
  7247. except:
  7248. # TODO: The return behavior has not been established... should raise exception?
  7249. return "Could not retrieve object: %s" % obj_name
  7250. else:
  7251. obj = local_use
  7252. # updated units
  7253. eunits = self.defaults["excellon_exp_units"]
  7254. ewhole = self.defaults["excellon_exp_integer"]
  7255. efract = self.defaults["excellon_exp_decimals"]
  7256. ezeros = self.defaults["excellon_exp_zeros"]
  7257. eformat = self.defaults["excellon_exp_format"]
  7258. slot_type = self.defaults["excellon_exp_slot_type"]
  7259. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7260. if fc_units == 'MM':
  7261. factor = 1 if eunits == 'METRIC' else 0.03937
  7262. else:
  7263. factor = 25.4 if eunits == 'METRIC' else 1
  7264. def make_excellon():
  7265. try:
  7266. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7267. header = 'M48\n'
  7268. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7269. (str(self.version), str(self.version_date))
  7270. header += ';Filename: %s' % str(obj_name) + '\n'
  7271. header += ';Created on : %s' % time_str + '\n'
  7272. if eformat == 'dec':
  7273. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7274. header += eunits + '\n'
  7275. for tool in obj.tools:
  7276. if eunits == 'METRIC':
  7277. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7278. tool=str(tool),
  7279. dec=2)
  7280. else:
  7281. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7282. tool=str(tool),
  7283. dec=4)
  7284. else:
  7285. if ezeros == 'LZ':
  7286. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7287. form='ndec', e_zeros='LZ', factor=factor,
  7288. slot_type=slot_type)
  7289. header += '%s,%s\n' % (eunits, 'LZ')
  7290. header += format_exc
  7291. for tool in obj.tools:
  7292. if eunits == 'METRIC':
  7293. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7294. tool=str(tool),
  7295. dec=2)
  7296. else:
  7297. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7298. tool=str(tool),
  7299. dec=4)
  7300. else:
  7301. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7302. form='ndec', e_zeros='TZ', factor=factor,
  7303. slot_type=slot_type)
  7304. header += '%s,%s\n' % (eunits, 'TZ')
  7305. header += format_exc
  7306. for tool in obj.tools:
  7307. if eunits == 'METRIC':
  7308. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7309. tool=str(tool),
  7310. dec=2)
  7311. else:
  7312. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7313. tool=str(tool),
  7314. dec=4)
  7315. header += '%\n'
  7316. footer = 'M30\n'
  7317. exported_excellon = header
  7318. exported_excellon += excellon_code
  7319. exported_excellon += footer
  7320. if local_use is None:
  7321. try:
  7322. with open(filename, 'w') as fp:
  7323. fp.write(exported_excellon)
  7324. except PermissionError:
  7325. self.inform.emit('[WARNING] %s' %
  7326. _("Permission denied, saving not possible.\n"
  7327. "Most likely another app is holding the file open and not accessible."))
  7328. return 'fail'
  7329. if self.defaults["global_open_style"] is False:
  7330. self.file_opened.emit("Excellon", filename)
  7331. self.file_saved.emit("Excellon", filename)
  7332. self.inform.emit('[success] %s: %s' %
  7333. (_("Excellon file exported to"), filename))
  7334. else:
  7335. return exported_excellon
  7336. except Exception as e:
  7337. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7338. return 'fail'
  7339. if use_thread is True:
  7340. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7341. def job_thread_exc(app_obj):
  7342. ret = make_excellon()
  7343. if ret == 'fail':
  7344. self.inform.emit('[ERROR_NOTCL] %s' %
  7345. _('Could not export Excellon file.'))
  7346. return
  7347. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7348. else:
  7349. ret = make_excellon()
  7350. if ret == 'fail':
  7351. self.inform.emit('[ERROR_NOTCL] %s' %
  7352. _('Could not export Excellon file.'))
  7353. return 'fail'
  7354. if local_use is not None:
  7355. return ret
  7356. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7357. """
  7358. Exports a Gerber Object to an Gerber file.
  7359. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7360. :param filename: Path to the Gerber file to save to.
  7361. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7362. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7363. :param use_thread: if to be run in a separate thread
  7364. :return:
  7365. """
  7366. self.report_usage("export_gerber()")
  7367. if filename is None:
  7368. filename = self.defaults["global_last_save_folder"]
  7369. self.log.debug("export_gerber()")
  7370. if local_use is None:
  7371. try:
  7372. obj = self.collection.get_by_name(str(obj_name))
  7373. except:
  7374. # TODO: The return behavior has not been established... should raise exception?
  7375. return "Could not retrieve object: %s" % obj_name
  7376. else:
  7377. obj = local_use
  7378. # updated units
  7379. gunits = self.defaults["gerber_exp_units"]
  7380. gwhole = self.defaults["gerber_exp_integer"]
  7381. gfract = self.defaults["gerber_exp_decimals"]
  7382. gzeros = self.defaults["gerber_exp_zeros"]
  7383. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7384. if fc_units == 'MM':
  7385. factor = 1 if gunits == 'MM' else 0.03937
  7386. else:
  7387. factor = 25.4 if gunits == 'MM' else 1
  7388. def make_gerber():
  7389. try:
  7390. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7391. header = 'G04*\n'
  7392. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7393. (str(self.version), str(self.version_date))
  7394. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7395. header += 'G04 Created on : %s*' % time_str + '\n'
  7396. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7397. header += "%MO{units}*%\n".format(units=gunits)
  7398. for apid in obj.apertures:
  7399. if obj.apertures[apid]['type'] == 'C':
  7400. header += "%ADD{apid}{type},{size}*%\n".format(
  7401. apid=str(apid),
  7402. type='C',
  7403. size=(factor * obj.apertures[apid]['size'])
  7404. )
  7405. elif obj.apertures[apid]['type'] == 'R':
  7406. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7407. apid=str(apid),
  7408. type='R',
  7409. width=(factor * obj.apertures[apid]['width']),
  7410. height=(factor * obj.apertures[apid]['height'])
  7411. )
  7412. elif obj.apertures[apid]['type'] == 'O':
  7413. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7414. apid=str(apid),
  7415. type='O',
  7416. width=(factor * obj.apertures[apid]['width']),
  7417. height=(factor * obj.apertures[apid]['height'])
  7418. )
  7419. header += '\n'
  7420. # obsolete units but some software may need it
  7421. if gunits == 'IN':
  7422. header += 'G70*\n'
  7423. else:
  7424. header += 'G71*\n'
  7425. # Absolute Mode
  7426. header += 'G90*\n'
  7427. header += 'G01*\n'
  7428. # positive polarity
  7429. header += '%LPD*%\n'
  7430. footer = 'M02*\n'
  7431. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7432. exported_gerber = header
  7433. exported_gerber += gerber_code
  7434. exported_gerber += footer
  7435. if local_use is None:
  7436. try:
  7437. with open(filename, 'w') as fp:
  7438. fp.write(exported_gerber)
  7439. except PermissionError:
  7440. self.inform.emit('[WARNING] %s' %
  7441. _("Permission denied, saving not possible.\n"
  7442. "Most likely another app is holding the file open and not accessible."))
  7443. return 'fail'
  7444. if self.defaults["global_open_style"] is False:
  7445. self.file_opened.emit("Gerber", filename)
  7446. self.file_saved.emit("Gerber", filename)
  7447. self.inform.emit('[success] %s: %s' %
  7448. (_("Gerber file exported to"), filename))
  7449. else:
  7450. return exported_gerber
  7451. except Exception as e:
  7452. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7453. return 'fail'
  7454. if use_thread is True:
  7455. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7456. def job_thread_grb(app_obj):
  7457. ret = make_gerber()
  7458. if ret == 'fail':
  7459. self.inform.emit('[ERROR_NOTCL] %s' %
  7460. _('Could not export Gerber file.'))
  7461. return
  7462. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7463. else:
  7464. ret = make_gerber()
  7465. if ret == 'fail':
  7466. self.inform.emit('[ERROR_NOTCL] %s' %
  7467. _('Could not export Gerber file.'))
  7468. return 'fail'
  7469. if local_use is not None:
  7470. return ret
  7471. def export_dxf(self, obj_name, filename, use_thread=True):
  7472. """
  7473. Exports a Geometry Object to an DXF file.
  7474. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7475. :param filename: Path to the DXF file to save to.
  7476. :param use_thread: if to be run in a separate thread
  7477. :return:
  7478. """
  7479. self.report_usage("export_dxf()")
  7480. if filename is None:
  7481. filename = self.defaults["global_last_save_folder"]
  7482. self.log.debug("export_dxf()")
  7483. format_exc = ''
  7484. units = ''
  7485. try:
  7486. obj = self.collection.get_by_name(str(obj_name))
  7487. except:
  7488. # TODO: The return behavior has not been established... should raise exception?
  7489. return "Could not retrieve object: %s" % obj_name
  7490. # updated units
  7491. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7492. if units == 'IN' or units == 'INCH':
  7493. units = 'INCH'
  7494. elif units == 'MM' or units == 'METIRC':
  7495. units ='METRIC'
  7496. def make_dxf():
  7497. try:
  7498. dxf_code = obj.export_dxf()
  7499. dxf_code.saveas(filename)
  7500. if self.defaults["global_open_style"] is False:
  7501. self.file_opened.emit("DXF", filename)
  7502. self.file_saved.emit("DXF", filename)
  7503. self.inform.emit('[success] %s: %s' %
  7504. (_("DXF file exported to"), filename))
  7505. except:
  7506. return 'fail'
  7507. if use_thread is True:
  7508. with self.proc_container.new(_("Exporting DXF")) as proc:
  7509. def job_thread_exc(app_obj):
  7510. ret = make_dxf()
  7511. if ret == 'fail':
  7512. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7513. _('Could not export DXF file.'))
  7514. return
  7515. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7516. else:
  7517. ret = make_dxf()
  7518. if ret == 'fail':
  7519. self.inform.emit('[WARNING_NOTCL] %s' %
  7520. _('Could not export DXF file.'))
  7521. return
  7522. def import_svg(self, filename, geo_type='geometry', outname=None):
  7523. """
  7524. Adds a new Geometry Object to the projects and populates
  7525. it with shapes extracted from the SVG file.
  7526. :param filename: Path to the SVG file.
  7527. :param outname:
  7528. :return:
  7529. """
  7530. self.report_usage("import_svg()")
  7531. obj_type = ""
  7532. if geo_type is None or geo_type == "geometry":
  7533. obj_type = "geometry"
  7534. elif geo_type == "gerber":
  7535. obj_type = geo_type
  7536. else:
  7537. self.inform.emit('[ERROR_NOTCL] %s' %
  7538. _("Not supported type is picked as parameter. "
  7539. "Only Geometry and Gerber are supported"))
  7540. return
  7541. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7542. def obj_init(geo_obj, app_obj):
  7543. geo_obj.import_svg(filename, obj_type, units=units)
  7544. geo_obj.multigeo = False
  7545. with self.proc_container.new(_("Importing SVG")) as proc:
  7546. # Object name
  7547. name = outname or filename.split('/')[-1].split('\\')[-1]
  7548. self.new_object(obj_type, name, obj_init, autoselected=False)
  7549. self.progress.emit(20)
  7550. # Register recent file
  7551. self.file_opened.emit("svg", filename)
  7552. # GUI feedback
  7553. self.inform.emit('[success] %s: %s' %
  7554. (_("Opened"), filename))
  7555. self.progress.emit(100)
  7556. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7557. """
  7558. Adds a new Geometry Object to the projects and populates
  7559. it with shapes extracted from the DXF file.
  7560. :param filename: Path to the DXF file.
  7561. :param outname:
  7562. :type putname: str
  7563. :return:
  7564. """
  7565. self.report_usage("import_dxf()")
  7566. obj_type = ""
  7567. if geo_type is None or geo_type == "geometry":
  7568. obj_type = "geometry"
  7569. elif geo_type == "gerber":
  7570. obj_type = geo_type
  7571. else:
  7572. self.inform.emit('[ERROR_NOTCL] %s' %
  7573. _("Not supported type is picked as parameter. "
  7574. "Only Geometry and Gerber are supported"))
  7575. return
  7576. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7577. def obj_init(geo_obj, app_obj):
  7578. geo_obj.import_dxf(filename, obj_type, units=units)
  7579. geo_obj.multigeo = False
  7580. with self.proc_container.new(_("Importing DXF")) as proc:
  7581. # Object name
  7582. name = outname or filename.split('/')[-1].split('\\')[-1]
  7583. self.new_object(obj_type, name, obj_init, autoselected=False)
  7584. self.progress.emit(20)
  7585. # Register recent file
  7586. self.file_opened.emit("dxf", filename)
  7587. # GUI feedback
  7588. self.inform.emit('[success] %s: %s' %
  7589. (_("Opened"), filename))
  7590. self.progress.emit(100)
  7591. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7592. """
  7593. Adds a new Geometry Object to the projects and populates
  7594. it with shapes extracted from the SVG file.
  7595. :param filename: Path to the SVG file.
  7596. :param o_type: type of FlatCAM objeect
  7597. :param dpi: dot per inch
  7598. :param mode: black or color
  7599. :param mask: dictate the level of detail
  7600. :param outname: name for the resulting file
  7601. :return:
  7602. """
  7603. self.report_usage("import_image()")
  7604. if o_type is None or o_type == "geometry":
  7605. obj_type = "geometry"
  7606. elif o_type == "gerber":
  7607. obj_type = o_type
  7608. else:
  7609. self.inform.emit('[ERROR_NOTCL] %s' %
  7610. _("Not supported type is picked as parameter. "
  7611. "Only Geometry and Gerber are supported"))
  7612. return
  7613. def obj_init(geo_obj, app_obj):
  7614. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7615. geo_obj.multigeo = False
  7616. with self.proc_container.new(_("Importing Image")) as proc:
  7617. # Object name
  7618. name = outname or filename.split('/')[-1].split('\\')[-1]
  7619. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7620. self.new_object(obj_type, name, obj_init)
  7621. self.progress.emit(20)
  7622. # Register recent file
  7623. self.file_opened.emit("image", filename)
  7624. # GUI feedback
  7625. self.inform.emit('[success] %s: %s' %
  7626. (_("Opened"), filename))
  7627. self.progress.emit(100)
  7628. def open_gerber(self, filename, outname=None):
  7629. """
  7630. Opens a Gerber file, parses it and creates a new object for
  7631. it in the program. Thread-safe.
  7632. :param outname: Name of the resulting object. None causes the
  7633. name to be that of the file.
  7634. :param filename: Gerber file filename
  7635. :type filename: str
  7636. :param follow: If true, the parser will not create polygons, just lines
  7637. following the gerber path.
  7638. :type follow: bool
  7639. :return: None
  7640. """
  7641. # How the object should be initialized
  7642. def obj_init(gerber_obj, app_obj):
  7643. assert isinstance(gerber_obj, FlatCAMGerber), \
  7644. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7645. # Opening the file happens here
  7646. self.progress.emit(30)
  7647. try:
  7648. gerber_obj.parse_file(filename)
  7649. except IOError:
  7650. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7651. (_("Failed to open file"), filename))
  7652. app_obj.progress.emit(0)
  7653. return "fail"
  7654. except ParseError as err:
  7655. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  7656. (_("Failed to parse file"), filename, str(err)))
  7657. app_obj.progress.emit(0)
  7658. self.log.error(str(err))
  7659. return "fail"
  7660. except Exception as e:
  7661. log.debug("App.open_gerber() --> %s" % str(e))
  7662. msg = '[ERROR] %s' % \
  7663. _("An internal error has occurred. See shell.\n")
  7664. msg += traceback.format_exc()
  7665. app_obj.inform.emit(msg)
  7666. return "fail"
  7667. if gerber_obj.is_empty():
  7668. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7669. # self.collection.set_active(gerber_obj.options["name"])
  7670. # self.collection.delete_active()
  7671. self.inform.emit('[ERROR_NOTCL] %s' %
  7672. _("Object is not Gerber file or empty. Aborting object creation."))
  7673. return "fail"
  7674. # Further parsing
  7675. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7676. App.log.debug("open_gerber()")
  7677. with self.proc_container.new(_("Opening Gerber")) as proc:
  7678. self.progress.emit(10)
  7679. # Object name
  7680. name = outname or filename.split('/')[-1].split('\\')[-1]
  7681. # # ## Object creation # ##
  7682. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7683. if ret == 'fail':
  7684. self.inform.emit('[ERROR_NOTCL]%s' %
  7685. _(' Open Gerber failed. Probable not a Gerber file.'))
  7686. return
  7687. # Register recent file
  7688. self.file_opened.emit("gerber", filename)
  7689. self.progress.emit(100)
  7690. # GUI feedback
  7691. self.inform.emit('[success] %s: %s' %
  7692. (_("Opened"), filename))
  7693. def open_excellon(self, filename, outname=None):
  7694. """
  7695. Opens an Excellon file, parses it and creates a new object for
  7696. it in the program. Thread-safe.
  7697. :param outname: Name of the resulting object. None causes the
  7698. name to be that of the file.
  7699. :param filename: Excellon file filename
  7700. :type filename: str
  7701. :return: None
  7702. """
  7703. App.log.debug("open_excellon()")
  7704. # How the object should be initialized
  7705. def obj_init(excellon_obj, app_obj):
  7706. # self.progress.emit(20)
  7707. try:
  7708. ret = excellon_obj.parse_file(filename=filename)
  7709. if ret == "fail":
  7710. log.debug("Excellon parsing failed.")
  7711. self.inform.emit('[ERROR_NOTCL] %s' %
  7712. _("This is not Excellon file."))
  7713. return "fail"
  7714. except IOError:
  7715. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7716. (_("Cannot open file"), filename))
  7717. log.debug("Could not open Excellon object.")
  7718. self.progress.emit(0) # TODO: self and app_bjj mixed
  7719. return "fail"
  7720. except:
  7721. msg = '[ERROR_NOTCL] %s' % \
  7722. _("An internal error has occurred. See shell.\n")
  7723. msg += traceback.format_exc()
  7724. app_obj.inform.emit(msg)
  7725. return "fail"
  7726. ret = excellon_obj.create_geometry()
  7727. if ret == 'fail':
  7728. log.debug("Could not create geometry for Excellon object.")
  7729. return "fail"
  7730. for tool in excellon_obj.tools:
  7731. if excellon_obj.tools[tool]['solid_geometry']:
  7732. return
  7733. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7734. (_("No geometry found in file"), filename))
  7735. return "fail"
  7736. with self.proc_container.new(_("Opening Excellon.")):
  7737. # Object name
  7738. name = outname or filename.split('/')[-1].split('\\')[-1]
  7739. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  7740. if ret_val == 'fail':
  7741. self.inform.emit('[ERROR_NOTCL] %s' %
  7742. _('Open Excellon file failed. Probable not an Excellon file.'))
  7743. return
  7744. # Register recent file
  7745. self.file_opened.emit("excellon", filename)
  7746. # GUI feedback
  7747. self.inform.emit('[success] %s: %s' %
  7748. (_("Opened"), filename))
  7749. def open_gcode(self, filename, outname=None):
  7750. """
  7751. Opens a G-gcode file, parses it and creates a new object for
  7752. it in the program. Thread-safe.
  7753. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7754. :param filename: G-code file filename
  7755. :type filename: str
  7756. :return: None
  7757. """
  7758. App.log.debug("open_gcode()")
  7759. # How the object should be initialized
  7760. def obj_init(job_obj, app_obj_):
  7761. """
  7762. :param job_obj: the resulting object
  7763. :type app_obj_: App
  7764. """
  7765. assert isinstance(app_obj_, App), \
  7766. "Initializer expected App, got %s" % type(app_obj_)
  7767. self.progress.emit(10)
  7768. try:
  7769. f = open(filename)
  7770. gcode = f.read()
  7771. f.close()
  7772. except IOError:
  7773. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7774. (_("Failed to open"), filename))
  7775. self.progress.emit(0)
  7776. return "fail"
  7777. job_obj.gcode = gcode
  7778. self.progress.emit(20)
  7779. ret = job_obj.gcode_parse()
  7780. if ret == "fail":
  7781. self.inform.emit('[ERROR_NOTCL] %s' %
  7782. _("This is not GCODE"))
  7783. return "fail"
  7784. self.progress.emit(60)
  7785. job_obj.create_geometry()
  7786. with self.proc_container.new(_("Opening G-Code.")):
  7787. # Object name
  7788. name = outname or filename.split('/')[-1].split('\\')[-1]
  7789. # New object creation and file processing
  7790. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  7791. if ret == 'fail':
  7792. self.inform.emit('[ERROR_NOTCL] %s' %
  7793. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  7794. "Attempting to create a FlatCAM CNCJob Object from "
  7795. "G-Code file failed during processing"))
  7796. return "fail"
  7797. # Register recent file
  7798. self.file_opened.emit("cncjob", filename)
  7799. # GUI feedback
  7800. self.inform.emit('[success] %s: %s' %
  7801. (_("Opened"), filename))
  7802. self.progress.emit(100)
  7803. def open_config_file(self, filename, run_from_arg=None):
  7804. """
  7805. Loads a config file from the specified file.
  7806. :param filename: Name of the file from which to load.
  7807. :type filename: str
  7808. :return: None
  7809. """
  7810. App.log.debug("Opening config file: " + filename)
  7811. # add the tab if it was closed
  7812. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  7813. # first clear previous text in text editor (if any)
  7814. self.ui.code_editor.clear()
  7815. # Switch plot_area to CNCJob tab
  7816. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7817. try:
  7818. if filename:
  7819. f = QtCore.QFile(filename)
  7820. if f.open(QtCore.QIODevice.ReadOnly):
  7821. stream = QtCore.QTextStream(f)
  7822. gcode_edited = stream.readAll()
  7823. self.ui.code_editor.setPlainText(gcode_edited)
  7824. f.close()
  7825. except IOError:
  7826. App.log.error("Failed to open config file: %s" % filename)
  7827. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7828. (_("Failed to open config file"), filename))
  7829. return
  7830. def open_project(self, filename, run_from_arg=None):
  7831. """
  7832. Loads a project from the specified file.
  7833. 1) Loads and parses file
  7834. 2) Registers the file as recently opened.
  7835. 3) Calls on_file_new()
  7836. 4) Updates options
  7837. 5) Calls new_object() with the object's from_dict() as init method.
  7838. 6) Calls plot_all()
  7839. :param filename: Name of the file from which to load.
  7840. :type filename: str
  7841. :param run_from_arg: True if run for arguments
  7842. :return: None
  7843. """
  7844. App.log.debug("Opening project: " + filename)
  7845. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7846. # Open and parse an uncompressed Project file
  7847. try:
  7848. f = open(filename, 'r')
  7849. except IOError:
  7850. App.log.error("Failed to open project file: %s" % filename)
  7851. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7852. (_("Failed to open project file"), filename))
  7853. return
  7854. try:
  7855. d = json.load(f, object_hook=dict2obj)
  7856. except Exception as e:
  7857. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7858. (filename, str(e)))
  7859. f.close()
  7860. # Open and parse a compressed Project file
  7861. try:
  7862. with lzma.open(filename) as f:
  7863. file_content = f.read().decode('utf-8')
  7864. d = json.loads(file_content, object_hook=dict2obj)
  7865. except Exception as e:
  7866. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7867. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7868. (_("Failed to open project file"), filename))
  7869. return
  7870. # Clear the current project
  7871. # # NOT THREAD SAFE # ##
  7872. if run_from_arg is True:
  7873. pass
  7874. else:
  7875. self.on_file_new()
  7876. # Project options
  7877. self.options.update(d['options'])
  7878. self.project_filename = filename
  7879. self.set_screen_units(self.options["units"])
  7880. # Re create objects
  7881. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7882. for obj in d['objs']:
  7883. def obj_init(obj_inst, app_inst):
  7884. obj_inst.from_dict(obj)
  7885. App.log.debug("Recreating from opened project an %s object: %s" %
  7886. (obj['kind'].capitalize(), obj['options']['name']))
  7887. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7888. obj['kind'].upper(),
  7889. obj['options']['name']
  7890. )
  7891. )
  7892. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  7893. # self.plot_all()
  7894. self.inform.emit('[success] %s: %s' %
  7895. (_("Project loaded from"), filename))
  7896. self.should_we_save = False
  7897. self.file_opened.emit("project", filename)
  7898. self.set_ui_title(name=self.project_filename)
  7899. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7900. def propagate_defaults(self, silent=False):
  7901. """
  7902. This method is used to set default values in classes. It's
  7903. an alternative to project options but allows the use
  7904. of values invisible to the user.
  7905. :return: None
  7906. """
  7907. if silent is False:
  7908. self.log.debug("propagate_defaults()")
  7909. # Which objects to update the given parameters.
  7910. routes = {
  7911. "global_zdownrate": CNCjob,
  7912. "excellon_zeros": Excellon,
  7913. "excellon_format_upper_in": Excellon,
  7914. "excellon_format_lower_in": Excellon,
  7915. "excellon_format_upper_mm": Excellon,
  7916. "excellon_format_lower_mm": Excellon,
  7917. "excellon_units": Excellon,
  7918. "gerber_use_buffer_for_union": Gerber,
  7919. "geometry_multidepth": Geometry
  7920. }
  7921. for param in routes:
  7922. if param in routes[param].defaults:
  7923. try:
  7924. routes[param].defaults[param] = self.defaults[param]
  7925. if silent is False:
  7926. self.log.debug(" " + param + " OK")
  7927. except KeyError:
  7928. if silent is False:
  7929. self.log.debug(" ERROR: " + param + " not in defaults.")
  7930. else:
  7931. # Try extracting the name:
  7932. # classname_param here is param in the object
  7933. if param.find(routes[param].__name__.lower() + "_") == 0:
  7934. p = param[len(routes[param].__name__) + 1:]
  7935. if p in routes[param].defaults:
  7936. routes[param].defaults[p] = self.defaults[param]
  7937. if silent is False:
  7938. self.log.debug(" " + param + " OK!")
  7939. def restore_main_win_geom(self):
  7940. try:
  7941. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7942. self.defaults["global_def_win_y"],
  7943. self.defaults["global_def_win_w"],
  7944. self.defaults["global_def_win_h"])
  7945. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7946. settings = QSettings("Open Source", "FlatCAM")
  7947. if settings.contains("maximized_gui"):
  7948. maximized_ui = settings.value('maximized_gui', type=bool)
  7949. if maximized_ui is True:
  7950. self.ui.showMaximized()
  7951. except KeyError as e:
  7952. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7953. def plot_all(self, zoom=True):
  7954. """
  7955. Re-generates all plots from all objects.
  7956. :return: None
  7957. """
  7958. self.log.debug("Plot_all()")
  7959. for obj in self.collection.get_list():
  7960. def worker_task(obj):
  7961. with self.proc_container.new("Plotting"):
  7962. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7963. if zoom:
  7964. self.object_plotted.emit(obj)
  7965. # Send to worker
  7966. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7967. def register_folder(self, filename):
  7968. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7969. def register_save_folder(self, filename):
  7970. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7971. def set_progress_bar(self, percentage, text=""):
  7972. self.ui.progress_bar.setValue(int(percentage))
  7973. def setup_shell(self):
  7974. """
  7975. Creates shell functions. Runs once at startup.
  7976. :return: None
  7977. """
  7978. self.log.debug("setup_shell()")
  7979. def shelp(p=None):
  7980. if not p:
  7981. return _("Available commands:\n") + \
  7982. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7983. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7984. if p not in commands:
  7985. return "Unknown command: %s" % p
  7986. return commands[p]["help"]
  7987. # --- Migrated to new architecture ---
  7988. # def options(name):
  7989. # ops = self.collection.get_by_name(str(name)).options
  7990. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7991. def h(*args):
  7992. """
  7993. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7994. and standalone parameters into list.
  7995. """
  7996. kwa = {}
  7997. a = []
  7998. n = len(args)
  7999. name = None
  8000. for i in range(n):
  8001. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8002. if match:
  8003. assert name is None
  8004. name = match.group(1)
  8005. continue
  8006. if name is None:
  8007. a.append(args[i])
  8008. else:
  8009. kwa[name] = args[i]
  8010. name = None
  8011. return a, kwa
  8012. @contextmanager
  8013. def wait_signal(signal, timeout=10000):
  8014. """
  8015. Block loop until signal emitted, timeout (ms) elapses
  8016. or unhandled exception happens in a thread.
  8017. :param timeout: time after which the loop is exited
  8018. :param signal: Signal to wait for.
  8019. """
  8020. loop = QtCore.QEventLoop()
  8021. # Normal termination
  8022. signal.connect(loop.quit)
  8023. # Termination by exception in thread
  8024. self.thread_exception.connect(loop.quit)
  8025. status = {'timed_out': False}
  8026. def report_quit():
  8027. status['timed_out'] = True
  8028. loop.quit()
  8029. yield
  8030. # Temporarily change how exceptions are managed.
  8031. oeh = sys.excepthook
  8032. ex = []
  8033. def except_hook(type_, value, traceback_):
  8034. ex.append(value)
  8035. oeh(type_, value, traceback_)
  8036. sys.excepthook = except_hook
  8037. # Terminate on timeout
  8038. if timeout is not None:
  8039. QtCore.QTimer.singleShot(timeout, report_quit)
  8040. # # ## Block ## ##
  8041. loop.exec_()
  8042. # Restore exception management
  8043. sys.excepthook = oeh
  8044. if ex:
  8045. self.raiseTclError(str(ex[0]))
  8046. if status['timed_out']:
  8047. raise Exception('Timed out!')
  8048. def make_docs():
  8049. output = ''
  8050. import collections
  8051. od = collections.OrderedDict(sorted(commands.items()))
  8052. for cmd_, val in od.items():
  8053. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8054. t = val['help']
  8055. usage_i = t.find('>')
  8056. if usage_i < 0:
  8057. expl = t
  8058. output += expl + '\n\n'
  8059. continue
  8060. expl = t[:usage_i - 1]
  8061. output += expl + '\n\n'
  8062. end_usage_i = t[usage_i:].find('\n')
  8063. if end_usage_i < 0:
  8064. end_usage_i = len(t[usage_i:])
  8065. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8066. else:
  8067. extras = t[usage_i+end_usage_i+1:]
  8068. parts = [s.strip() for s in extras.split('\n')]
  8069. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8070. for p in parts:
  8071. output += ' ' + p + '\n\n'
  8072. return output
  8073. '''
  8074. Howto implement TCL shell commands:
  8075. All parameters passed to command should be possible to set as None and test it afterwards.
  8076. This is because we need to see error caused in tcl,
  8077. if None value as default parameter is not allowed TCL will return empty error.
  8078. Use:
  8079. def mycommand(name=None,...):
  8080. Test it like this:
  8081. if name is None:
  8082. self.raise_tcl_error('Argument name is missing.')
  8083. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8084. otherwise we will miss it and processing will silently continue.
  8085. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8086. which is catched in exec_command and displayed in TCL shell console with red background.
  8087. Error in console is displayed with TCL trace.
  8088. This behavior works only within main thread,
  8089. errors with promissed tasks can be catched and detected only with log.
  8090. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8091. TCL shell.
  8092. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8093. '''
  8094. commands = {
  8095. 'help': {
  8096. 'fcn': shelp,
  8097. 'help': _("Shows list of commands.")
  8098. },
  8099. }
  8100. # Import/overwrite tcl commands as objects of TclCommand descendants
  8101. # This modifies the variable 'commands'.
  8102. tclCommands.register_all_commands(self, commands)
  8103. # Add commands to the tcl interpreter
  8104. for cmd in commands:
  8105. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8106. # Make the tcl puts function return instead of print to stdout
  8107. self.tcl.eval('''
  8108. rename puts original_puts
  8109. proc puts {args} {
  8110. if {[llength $args] == 1} {
  8111. return "[lindex $args 0]"
  8112. } else {
  8113. eval original_puts $args
  8114. }
  8115. }
  8116. ''')
  8117. def setup_recent_items(self):
  8118. # TODO: Move this to constructor
  8119. icons = {
  8120. "gerber": "share/flatcam_icon16.png",
  8121. "excellon": "share/drill16.png",
  8122. 'geometry': "share/geometry16.png",
  8123. "cncjob": "share/cnc16.png",
  8124. "project": "share/project16.png",
  8125. "svg": "share/geometry16.png",
  8126. "dxf": "share/dxf16.png",
  8127. "pdf": "share/pdf32.png",
  8128. "image": "share/image16.png"
  8129. }
  8130. openers = {
  8131. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8132. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8133. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8134. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8135. 'project': self.open_project,
  8136. 'svg': self.import_svg,
  8137. 'dxf': self.import_dxf,
  8138. 'image': self.import_image,
  8139. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8140. }
  8141. # Open recent file for files
  8142. try:
  8143. f = open(self.data_path + '/recent.json')
  8144. except IOError:
  8145. App.log.error("Failed to load recent item list.")
  8146. self.inform.emit('[ERROR_NOTCL] %s' %
  8147. _("Failed to load recent item list."))
  8148. return
  8149. try:
  8150. self.recent = json.load(f)
  8151. except json.scanner.JSONDecodeError:
  8152. App.log.error("Failed to parse recent item list.")
  8153. self.inform.emit('[ERROR_NOTCL] %s' %
  8154. _("Failed to parse recent item list."))
  8155. f.close()
  8156. return
  8157. f.close()
  8158. # Open recent file for projects
  8159. try:
  8160. fp = open(self.data_path + '/recent_projects.json')
  8161. except IOError:
  8162. App.log.error("Failed to load recent project item list.")
  8163. self.inform.emit('[ERROR_NOTCL] %s' %
  8164. _("Failed to load recent projects item list."))
  8165. return
  8166. try:
  8167. self.recent_projects = json.load(fp)
  8168. except json.scanner.JSONDecodeError:
  8169. App.log.error("Failed to parse recent project item list.")
  8170. self.inform.emit('[ERROR_NOTCL] %s' %
  8171. _("Failed to parse recent project item list."))
  8172. fp.close()
  8173. return
  8174. fp.close()
  8175. # Closure needed to create callbacks in a loop.
  8176. # Otherwise late binding occurs.
  8177. def make_callback(func, fname):
  8178. def opener():
  8179. func(fname)
  8180. return opener
  8181. def reset_recent_files():
  8182. # Reset menu
  8183. self.ui.recent.clear()
  8184. self.recent = []
  8185. try:
  8186. f = open(self.data_path + '/recent.json', 'w')
  8187. except IOError:
  8188. App.log.error("Failed to open recent items file for writing.")
  8189. return
  8190. json.dump(self.recent, f)
  8191. def reset_recent_projects():
  8192. # Reset menu
  8193. self.ui.recent_projects.clear()
  8194. self.recent_projects = []
  8195. try:
  8196. fp = open(self.data_path + '/recent_projects.json', 'w')
  8197. except IOError:
  8198. App.log.error("Failed to open recent projects items file for writing.")
  8199. return
  8200. json.dump(self.recent, fp)
  8201. # Reset menu
  8202. self.ui.recent.clear()
  8203. self.ui.recent_projects.clear()
  8204. # Create menu items for projects
  8205. for recent in self.recent_projects:
  8206. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8207. if recent['kind'] == 'project':
  8208. try:
  8209. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8210. # Attach callback
  8211. o = make_callback(openers[recent["kind"]], recent['filename'])
  8212. action.triggered.connect(o)
  8213. self.ui.recent_projects.addAction(action)
  8214. except KeyError:
  8215. App.log.error("Unsupported file type: %s" % recent["kind"])
  8216. # Last action in Recent Files menu is one that Clear the content
  8217. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8218. clear_action_proj.triggered.connect(reset_recent_projects)
  8219. self.ui.recent_projects.addSeparator()
  8220. self.ui.recent_projects.addAction(clear_action_proj)
  8221. # Create menu items for files
  8222. for recent in self.recent:
  8223. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8224. if recent['kind'] != 'project':
  8225. try:
  8226. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8227. # Attach callback
  8228. o = make_callback(openers[recent["kind"]], recent['filename'])
  8229. action.triggered.connect(o)
  8230. self.ui.recent.addAction(action)
  8231. except KeyError:
  8232. App.log.error("Unsupported file type: %s" % recent["kind"])
  8233. # Last action in Recent Files menu is one that Clear the content
  8234. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8235. clear_action.triggered.connect(reset_recent_files)
  8236. self.ui.recent.addSeparator()
  8237. self.ui.recent.addAction(clear_action)
  8238. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8239. # self.ui.menufilerecent.set_submenu(recent_menu)
  8240. # recent_menu.show_all()
  8241. # self.ui.recent.show()
  8242. self.log.debug("Recent items list has been populated.")
  8243. def setup_component_editor(self):
  8244. # label = QtWidgets.QLabel("Choose an item from Project")
  8245. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8246. sel_title = QtWidgets.QTextEdit(
  8247. _('<b>Shortcut Key List</b>'))
  8248. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8249. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8250. settings = QSettings("Open Source", "FlatCAM")
  8251. if settings.contains("notebook_font_size"):
  8252. fsize = settings.value('notebook_font_size', type=int)
  8253. else:
  8254. fsize = 12
  8255. tsize = fsize + int(fsize / 2)
  8256. # selected_text = (_('''
  8257. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8258. #
  8259. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8260. # The normal flow when working in FlatCAM is the following:</span></p>
  8261. #
  8262. # <ol>
  8263. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8264. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8265. # even dragging and dropping the files on the GUI.<br />
  8266. # <br />
  8267. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8268. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8269. # &nbsp;</li>
  8270. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8271. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8272. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8273. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8274. # <br />
  8275. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8276. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8277. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8278. # it even if it was out of focus.<br />
  8279. # <br />
  8280. # You can change the parameters in this screen and the flow direction is like this:<br />
  8281. # <br />
  8282. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8283. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8284. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8285. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8286. # </ol>
  8287. #
  8288. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8289. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8290. # <strong>F3</strong>.</span></p>
  8291. #
  8292. # ''').format(fsize=fsize, tsize=tsize))
  8293. selected_text = '''
  8294. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8295. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8296. %s:</span></p>
  8297. <ol>
  8298. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8299. <br />
  8300. %s &amp; %s.</span><br />
  8301. &nbsp;</li>
  8302. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8303. <br />
  8304. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8305. <br />
  8306. %s:<br />
  8307. <br />
  8308. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8309. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8310. </ol>
  8311. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8312. <strong>F3</strong>.</span></p>
  8313. ''' % (
  8314. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8315. _("The normal flow when working in FlatCAM is the following"),
  8316. _("Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8317. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8318. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8319. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8320. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8321. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8322. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8323. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8324. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8325. _("SELECTED TAB"),
  8326. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8327. "double clicking on the object on the canvas will bring the"),
  8328. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8329. _("You can change the parameters in this screen and the flow direction is like this"),
  8330. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8331. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8332. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8333. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8334. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8335. )
  8336. sel_title.setText(selected_text)
  8337. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8338. self.ui.selected_scroll_area.setWidget(sel_title)
  8339. def setup_obj_classes(self):
  8340. """
  8341. Sets up application specifics on the FlatCAMObj class.
  8342. :return: None
  8343. """
  8344. FlatCAMObj.app = self
  8345. ObjectCollection.app = self
  8346. Gerber.app = self
  8347. Excellon.app = self
  8348. Geometry.app = self
  8349. CNCjob.app = self
  8350. FCProcess.app = self
  8351. FCProcessContainer.app = self
  8352. def version_check(self):
  8353. """
  8354. Checks for the latest version of the program. Alerts the
  8355. user if theirs is outdated. This method is meant to be run
  8356. in a separate thread.
  8357. :return: None
  8358. """
  8359. self.log.debug("version_check()")
  8360. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8361. full_url = App.version_url + \
  8362. "?s=" + str(self.defaults['global_serial']) + \
  8363. "&v=" + str(self.version) + \
  8364. "&os=" + str(self.os) + \
  8365. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8366. else:
  8367. # no_stats dict; just so it won't break things on website
  8368. no_ststs_dict = {}
  8369. no_ststs_dict["global_ststs"] = {}
  8370. full_url = App.version_url + \
  8371. "?s=" + str(self.defaults['global_serial']) + \
  8372. "&v=" + str(self.version) + \
  8373. "&os=" + str(self.os) + \
  8374. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8375. App.log.debug("Checking for updates @ %s" % full_url)
  8376. # ## Get the data
  8377. try:
  8378. f = urllib.request.urlopen(full_url)
  8379. except:
  8380. # App.log.warning("Failed checking for latest version. Could not connect.")
  8381. self.log.warning("Failed checking for latest version. Could not connect.")
  8382. self.inform.emit('[WARNING_NOTCL] %s' %
  8383. _("Failed checking for latest version. Could not connect."))
  8384. return
  8385. try:
  8386. data = json.load(f)
  8387. except Exception as e:
  8388. App.log.error("Could not parse information about latest version.")
  8389. self.inform.emit('[ERROR_NOTCL] %s' %
  8390. _("Could not parse information about latest version."))
  8391. App.log.debug("json.load(): %s" % str(e))
  8392. f.close()
  8393. return
  8394. f.close()
  8395. # ## Latest version?
  8396. if self.version >= data["version"]:
  8397. App.log.debug("FlatCAM is up to date!")
  8398. self.inform.emit('[success] %s' %
  8399. _("FlatCAM is up to date!"))
  8400. return
  8401. App.log.debug("Newer version available.")
  8402. self.message.emit(
  8403. _("Newer Version Available"),
  8404. _("There is a newer version of FlatCAM available for download:\n\n") +
  8405. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8406. _("info")
  8407. )
  8408. def on_plotcanvas_setup(self, container=None):
  8409. """
  8410. This is doing the setup for the plot area (VisPy canvas)
  8411. :param container: widget where to install the canvas
  8412. :return: None
  8413. """
  8414. if container:
  8415. plot_container = container
  8416. else:
  8417. plot_container = self.ui.right_layout
  8418. self.plotcanvas = PlotCanvas(plot_container, self)
  8419. # So it can receive key presses
  8420. self.plotcanvas.native.setFocus()
  8421. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8422. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8423. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8424. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8425. # Keys over plot enabled
  8426. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8427. self.app_cursor = self.plotcanvas.new_cursor()
  8428. self.app_cursor.enabled = False
  8429. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8430. def on_zoom_fit(self, event):
  8431. """
  8432. Callback for zoom-out request. This can be either from the corresponding
  8433. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8434. with axes limits from the geometry bounds of all objects.
  8435. :param event: Ignored.
  8436. :return: None
  8437. """
  8438. self.plotcanvas.fit_view()
  8439. def on_zoom_in(self):
  8440. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8441. def on_zoom_out(self):
  8442. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8443. def disable_all_plots(self):
  8444. self.report_usage("disable_all_plots()")
  8445. self.disable_plots(self.collection.get_list())
  8446. self.inform.emit('[success] %s' %
  8447. _("All plots disabled."))
  8448. def disable_other_plots(self):
  8449. self.report_usage("disable_other_plots()")
  8450. self.disable_plots(self.collection.get_non_selected())
  8451. self.inform.emit('[success] %s' %
  8452. _("All non selected plots disabled."))
  8453. def enable_all_plots(self):
  8454. self.report_usage("enable_all_plots()")
  8455. self.enable_plots(self.collection.get_list())
  8456. self.inform.emit('[success] %s' %
  8457. _("All plots enabled."))
  8458. def on_enable_sel_plots(self):
  8459. log.debug("App.on_enable_sel_plot()")
  8460. object_list = self.collection.get_selected()
  8461. self.enable_plots(objects=object_list)
  8462. self.inform.emit('[success] %s' %
  8463. _("Selected plots enabled..."))
  8464. def on_disable_sel_plots(self):
  8465. log.debug("App.on_disable_sel_plot()")
  8466. # self.inform.emit(_("Disabling plots ..."))
  8467. object_list = self.collection.get_selected()
  8468. self.disable_plots(objects=object_list)
  8469. self.inform.emit('[success] %s' %
  8470. _("Selected plots disabled..."))
  8471. def enable_plots(self, objects):
  8472. """
  8473. Disables plots
  8474. :param objects: list of Objects to be enabled
  8475. :return:
  8476. """
  8477. log.debug("Enabling plots ...")
  8478. # self.inform.emit(_("Working ..."))
  8479. for obj in objects:
  8480. if obj.options['plot'] is False:
  8481. obj.options.set_change_callback(lambda x: None)
  8482. obj.options['plot'] = True
  8483. obj.options.set_change_callback(obj.on_options_change)
  8484. def worker_task(objects):
  8485. with self.proc_container.new(_("Enabling plots ...")):
  8486. for obj in objects:
  8487. # obj.options['plot'] = True
  8488. if isinstance(obj, FlatCAMCNCjob):
  8489. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8490. else:
  8491. obj.plot(visible=True)
  8492. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8493. # self.plots_updated.emit()
  8494. def disable_plots(self, objects):
  8495. """
  8496. Disables plots
  8497. :param objects: list of Objects to be disabled
  8498. :return:
  8499. """
  8500. # if no objects selected then do nothing
  8501. if not self.collection.get_selected():
  8502. return
  8503. log.debug("Disabling plots ...")
  8504. # self.inform.emit(_("Working ..."))
  8505. for obj in objects:
  8506. if obj.options['plot'] is True:
  8507. obj.options.set_change_callback(lambda x: None)
  8508. obj.options['plot'] = False
  8509. obj.options.set_change_callback(obj.on_options_change)
  8510. try:
  8511. self.delete_selection_shape()
  8512. except Exception as e:
  8513. log.debug("App.disable_plots() --> %s" % str(e))
  8514. # self.plots_updated.emit()
  8515. def worker_task(objects):
  8516. with self.proc_container.new(_("Disabling plots ...")):
  8517. for obj in objects:
  8518. # obj.options['plot'] = True
  8519. if isinstance(obj, FlatCAMCNCjob):
  8520. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8521. else:
  8522. obj.plot(visible=False)
  8523. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8524. def toggle_plots(self, objects):
  8525. """
  8526. Toggle plots visibility
  8527. :param objects: list of Objects for which to be toggled the visibility
  8528. :return:
  8529. """
  8530. # if no objects selected then do nothing
  8531. if not self.collection.get_selected():
  8532. return
  8533. log.debug("Toggling plots ...")
  8534. self.inform.emit(_("Working ..."))
  8535. for obj in objects:
  8536. if obj.options['plot'] is False:
  8537. obj.options['plot'] = True
  8538. else:
  8539. obj.options['plot'] = False
  8540. self.plots_updated.emit()
  8541. def clear_plots(self):
  8542. objects = self.collection.get_list()
  8543. for obj in objects:
  8544. obj.clear(obj == objects[-1])
  8545. # Clear pool to free memory
  8546. self.clear_pool()
  8547. def generate_cnc_job(self, objects):
  8548. self.report_usage("generate_cnc_job()")
  8549. # for obj in objects:
  8550. # obj.generatecncjob()
  8551. for obj in objects:
  8552. obj.on_generatecnc_button_click()
  8553. def save_project(self, filename, quit_action=False):
  8554. """
  8555. Saves the current project to the specified file.
  8556. :param filename: Name of the file in which to save.
  8557. :type filename: str
  8558. :param quit_action: if the project saving will be followed by an app quit; boolean
  8559. :return: None
  8560. """
  8561. self.log.debug("save_project()")
  8562. self.save_in_progress = True
  8563. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8564. # Capture the latest changes
  8565. # Current object
  8566. try:
  8567. self.collection.get_active().read_form()
  8568. except:
  8569. self.log.debug("There was no active object")
  8570. pass
  8571. # Project options
  8572. self.options_read_form()
  8573. # Serialize the whole project
  8574. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8575. "options": self.options,
  8576. "version": self.version}
  8577. if self.defaults["global_save_compressed"] is True:
  8578. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8579. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8580. # # Write
  8581. f.write(g)
  8582. self.inform.emit('[success] %s: %s' %
  8583. (_("Project saved to"), filename))
  8584. else:
  8585. # Open file
  8586. try:
  8587. f = open(filename, 'w')
  8588. except IOError:
  8589. App.log.error("Failed to open file for saving: %s", filename)
  8590. return
  8591. # Write
  8592. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8593. f.close()
  8594. # verification of the saved project
  8595. # Open and parse
  8596. try:
  8597. saved_f = open(filename, 'r')
  8598. except IOError:
  8599. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8600. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8601. )
  8602. return
  8603. try:
  8604. saved_d = json.load(saved_f, object_hook=dict2obj)
  8605. except:
  8606. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8607. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8608. )
  8609. f.close()
  8610. return
  8611. saved_f.close()
  8612. if 'version' in saved_d:
  8613. self.inform.emit('[success] %s: %s' %
  8614. (_("Project saved to"), filename))
  8615. else:
  8616. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8617. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8618. )
  8619. settings = QSettings("Open Source", "FlatCAM")
  8620. lock_state = self.ui.lock_action.isChecked()
  8621. settings.setValue('toolbar_lock', lock_state)
  8622. # This will write the setting to the platform specific storage.
  8623. del settings
  8624. # if quit:
  8625. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8626. # t.start()
  8627. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8628. def start_delayed_quit(self, delay, filename, should_quit=None):
  8629. """
  8630. :param delay: period of checking if project file size is more than zero; in seconds
  8631. :param filename: the name of the project file to be checked periodically for size more than zero
  8632. :param should_quit: if the task finished will be followed by an app quit; boolean
  8633. :return:
  8634. """
  8635. to_quit = should_quit
  8636. self.save_timer = QtCore.QTimer()
  8637. self.save_timer.setInterval(delay)
  8638. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8639. self.save_timer.start()
  8640. def check_project_file_size(self, filename, should_quit=None):
  8641. """
  8642. :param filename: the name of the project file to be checked periodically for size more than zero
  8643. :param should_quit: will quit the app if True; boolean
  8644. :return:
  8645. """
  8646. try:
  8647. if os.stat(filename).st_size > 0:
  8648. self.save_in_progress = False
  8649. self.save_timer.stop()
  8650. if should_quit:
  8651. self.app_quit.emit()
  8652. except Exception as e:
  8653. traceback.print_exc()
  8654. def on_options_app2project(self):
  8655. """
  8656. Callback for Options->Transfer Options->App=>Project. Copies options
  8657. from application defaults to project defaults.
  8658. :return: None
  8659. """
  8660. self.report_usage("on_options_app2project")
  8661. self.defaults_read_form()
  8662. self.options.update(self.defaults)
  8663. self.options_write_form()
  8664. def on_options_project2app(self):
  8665. """
  8666. Callback for Options->Transfer Options->Project=>App. Copies options
  8667. from project defaults to application defaults.
  8668. :return: None
  8669. """
  8670. self.report_usage("on_options_project2app")
  8671. self.options_read_form()
  8672. self.defaults.update(self.options)
  8673. self.defaults_write_form()
  8674. def on_options_project2object(self):
  8675. """
  8676. Callback for Options->Transfer Options->Project=>Object. Copies options
  8677. from project defaults to the currently selected object.
  8678. :return: None
  8679. """
  8680. self.report_usage("on_options_project2object")
  8681. self.options_read_form()
  8682. obj = self.collection.get_active()
  8683. if obj is None:
  8684. self.inform.emit('[WARNING_NOTCL] %s' %
  8685. _("No object selected."))
  8686. return
  8687. for option in self.options:
  8688. if option.find(obj.kind + "_") == 0:
  8689. oname = option[len(obj.kind) + 1:]
  8690. obj.options[oname] = self.options[option]
  8691. obj.to_form() # Update UI
  8692. def on_options_object2project(self):
  8693. """
  8694. Callback for Options->Transfer Options->Object=>Project. Copies options
  8695. from the currently selected object to project defaults.
  8696. :return: None
  8697. """
  8698. self.report_usage("on_options_object2project")
  8699. obj = self.collection.get_active()
  8700. if obj is None:
  8701. self.inform.emit('[WARNING_NOTCL] %s' %
  8702. _("No object selected."))
  8703. return
  8704. obj.read_form()
  8705. for option in obj.options:
  8706. if option in ['name']: # TODO: Handle this better...
  8707. continue
  8708. self.options[obj.kind + "_" + option] = obj.options[option]
  8709. self.options_write_form()
  8710. def on_options_object2app(self):
  8711. """
  8712. Callback for Options->Transfer Options->Object=>App. Copies options
  8713. from the currently selected object to application defaults.
  8714. :return: None
  8715. """
  8716. self.report_usage("on_options_object2app")
  8717. obj = self.collection.get_active()
  8718. if obj is None:
  8719. self.inform.emit('[WARNING_NOTCL] %s' %
  8720. _("No object selected."))
  8721. return
  8722. obj.read_form()
  8723. for option in obj.options:
  8724. if option in ['name']: # TODO: Handle this better...
  8725. continue
  8726. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8727. self.defaults_write_form()
  8728. def on_options_app2object(self):
  8729. """
  8730. Callback for Options->Transfer Options->App=>Object. Copies options
  8731. from application defaults to the currently selected object.
  8732. :return: None
  8733. """
  8734. self.report_usage("on_options_app2object")
  8735. self.defaults_read_form()
  8736. obj = self.collection.get_active()
  8737. if obj is None:
  8738. self.inform.emit('[WARNING_NOTCL] %s' %
  8739. _("No object selected."))
  8740. return
  8741. for option in self.defaults:
  8742. if option.find(obj.kind + "_") == 0:
  8743. oname = option[len(obj.kind) + 1:]
  8744. obj.options[oname] = self.defaults[option]
  8745. obj.to_form() # Update UI
  8746. class ArgsThread(QtCore.QObject):
  8747. open_signal = pyqtSignal(list)
  8748. start = pyqtSignal()
  8749. if sys.platform == 'win32':
  8750. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8751. else:
  8752. address = ('/tmp/testipc', 'AF_UNIX')
  8753. def __init__(self):
  8754. super(ArgsThread, self).__init__()
  8755. self.start.connect(self.run)
  8756. def my_loop(self, address):
  8757. try:
  8758. listener = Listener(*address)
  8759. while True:
  8760. conn = listener.accept()
  8761. self.serve(conn)
  8762. except socket.error as e:
  8763. conn = Client(*address)
  8764. conn.send(sys.argv)
  8765. conn.send('close')
  8766. # close the current instance only if there are args
  8767. if len(sys.argv) > 1:
  8768. sys.exit()
  8769. def serve(self, conn):
  8770. while True:
  8771. msg = conn.recv()
  8772. if msg == 'close':
  8773. break
  8774. self.open_signal.emit(msg)
  8775. conn.close()
  8776. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8777. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8778. @pyqtSlot()
  8779. def run(self):
  8780. self.my_loop(self.address)
  8781. class GracefulException(Exception):
  8782. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  8783. def __init__(self):
  8784. super().__init__()
  8785. def __str__(self):
  8786. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  8787. # end of file