FlatCAMApp.py 483 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886
  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 shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. super().__init__()
  229. App.log.info("FlatCAM Starting...")
  230. self.main_thread = QtWidgets.QApplication.instance().thread()
  231. # ############################################################################################################
  232. # ################# Setup the listening thread for another instance launching with args ######################
  233. # ############################################################################################################
  234. if sys.platform == 'win32' or sys.platform == 'linux':
  235. # make sure the thread is stored by using a self. otherwise it's garbage collected
  236. self.th = QtCore.QThread()
  237. self.th.start(priority=QtCore.QThread.LowestPriority)
  238. self.new_launch = ArgsThread()
  239. self.new_launch.open_signal[list].connect(self.on_startup_args)
  240. self.new_launch.moveToThread(self.th)
  241. self.new_launch.start.emit()
  242. # ############################################################################################################
  243. # # ######################################## OS-specific #####################################################
  244. # ############################################################################################################
  245. portable = False
  246. # Folder for user settings.
  247. if sys.platform == 'win32':
  248. if platform.architecture()[0] == '32bit':
  249. App.log.debug("Win32!")
  250. else:
  251. App.log.debug("Win64!")
  252. # #######################################################################################################
  253. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  254. # #######################################################################################################
  255. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  256. try:
  257. with open(config_file, 'r'):
  258. pass
  259. except FileNotFoundError:
  260. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  261. try:
  262. with open(config_file, 'r') as f:
  263. try:
  264. for line in f:
  265. param = str(line).replace('\n', '').rpartition('=')
  266. if param[0] == 'portable':
  267. try:
  268. portable = eval(param[2])
  269. except NameError:
  270. portable = False
  271. if param[0] == 'headless':
  272. if param[2].lower() == 'true':
  273. self.cmd_line_headless = 1
  274. else:
  275. self.cmd_line_headless = None
  276. except Exception as e:
  277. log.debug('App.__init__() -->%s' % str(e))
  278. return
  279. except FileNotFoundError as e:
  280. log.debug(str(e))
  281. pass
  282. if portable is False:
  283. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  284. else:
  285. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  286. self.os = 'windows'
  287. else: # Linux/Unix/MacOS
  288. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  289. self.os = 'unix'
  290. # ############################################################################################################
  291. # ################################# Setup folders and files ##################################################
  292. # ############################################################################################################
  293. if not os.path.exists(self.data_path):
  294. os.makedirs(self.data_path)
  295. App.log.debug('Created data folder: ' + self.data_path)
  296. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  297. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  298. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  299. if not os.path.exists(self.preprocessorpaths):
  300. os.makedirs(self.preprocessorpaths)
  301. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  302. # create geo_tools_db.FlatDB file if there is none
  303. try:
  304. f = open(self.data_path + '/geo_tools_db.FlatDB')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty geo_tool_db.FlatDB')
  308. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # create current_defaults.FlatConfig file if there is none
  312. try:
  313. f = open(self.data_path + '/current_defaults.FlatConfig')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty current_defaults.FlatConfig')
  317. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  318. json.dump({}, f)
  319. f.close()
  320. # Write factory_defaults.FlatConfig file to disk
  321. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  322. # create a recent files json file if there is none
  323. try:
  324. f = open(self.data_path + '/recent.json')
  325. f.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent.json')
  328. f = open(self.data_path + '/recent.json', 'w')
  329. json.dump([], f)
  330. f.close()
  331. # create a recent projects json file if there is none
  332. try:
  333. fp = open(self.data_path + '/recent_projects.json')
  334. fp.close()
  335. except IOError:
  336. App.log.debug('Creating empty recent_projects.json')
  337. fp = open(self.data_path + '/recent_projects.json', 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load
  341. # GUI icons will fail as their path is relative.
  342. # This will fail under cx_freeze ...
  343. self.app_home = os.path.dirname(os.path.realpath(__file__))
  344. App.log.debug("Application path is " + self.app_home)
  345. App.log.debug("Started in " + os.getcwd())
  346. # cx_freeze workaround
  347. if os.path.isfile(self.app_home):
  348. self.app_home = os.path.dirname(self.app_home)
  349. os.chdir(self.app_home)
  350. # ############################################################################################################
  351. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  352. # ############################################################################################################
  353. self.defaults = FlatCAMDefaults()
  354. self.defaults["root_folder_path"] = self.app_home
  355. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  356. if user_defaults:
  357. self.defaults.load(filename=current_defaults_path)
  358. if self.defaults['units'] == 'MM':
  359. self.decimals = int(self.defaults['decimals_metric'])
  360. else:
  361. self.decimals = int(self.defaults['decimals_inch'])
  362. if self.defaults["global_gray_icons"] is False:
  363. self.resource_location = 'assets/resources'
  364. else:
  365. self.resource_location = 'assets/resources/dark_resources'
  366. self.current_units = self.defaults['units']
  367. # ###########################################################################################################
  368. # #################################### SETUP OBJECT CLASSES #################################################
  369. # ###########################################################################################################
  370. self.setup_obj_classes()
  371. # ###########################################################################################################
  372. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  373. # ###########################################################################################################
  374. self.pool = Pool()
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  425. self.ui.final_save.connect(self.final_save)
  426. # restore the toolbar view
  427. self.restore_toolbar_view()
  428. # restore the GUI geometry
  429. self.restore_main_win_geom()
  430. # set FlatCAM units in the Status bar
  431. self.set_screen_units(self.defaults['units'])
  432. # ###########################################################################################################
  433. # ########################################### AUTOSAVE SETUP ################################################
  434. # ###########################################################################################################
  435. self.block_autosave = False
  436. self.autosave_timer = QtCore.QTimer(self)
  437. self.save_project_auto_update()
  438. self.autosave_timer.timeout.connect(self.save_project_auto)
  439. # ###########################################################################################################
  440. # #################################### LOAD PREPROCESSORS ###################################################
  441. # ###########################################################################################################
  442. # ----------------------------------------- WARNING --------------------------------------------------------
  443. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  444. # That's because the number of preprocessors can vary and here the comboboxes are populated
  445. # -----------------------------------------------------------------------------------------------------------
  446. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  447. # the preprocessor file
  448. self.preprocessors = load_preprocessors(self)
  449. # make sure that always the 'default' preprocessor is the first item in the dictionary
  450. if 'default' in self.preprocessors.keys():
  451. new_ppp_dict = {}
  452. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  453. default_pp = self.preprocessors.pop('default')
  454. new_ppp_dict['default'] = default_pp
  455. # then add the rest of the keys
  456. for name, val_class in self.preprocessors.items():
  457. new_ppp_dict[name] = val_class
  458. # and now put back the ordered dict with 'default' key first
  459. self.preprocessors = new_ppp_dict
  460. for name in list(self.preprocessors.keys()):
  461. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  462. if name.partition('_')[0] == 'Paste':
  463. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  464. continue
  465. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  466. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  467. if name == 'hpgl':
  468. continue
  469. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  470. # ###########################################################################################################
  471. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  472. # ###########################################################################################################
  473. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  474. inform=self.inform)
  475. self.preferencesUiManager.defaults_write_form()
  476. # When the self.defaults dictionary changes will update the Preferences GUI forms
  477. self.defaults.set_change_callback(self.on_defaults_dict_change)
  478. # ###########################################################################################################
  479. # ##################################### FIRST RUN SECTION ###################################################
  480. # ################################ It's done only once after install #####################################
  481. # ###########################################################################################################
  482. if self.defaults["first_run"] is True:
  483. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  484. initial_lay = 'minimal'
  485. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  486. # Set the combobox in Preferences to the current layout
  487. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  488. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  489. # after the first run, this object should be False
  490. self.defaults["first_run"] = False
  491. self.preferencesUiManager.save_defaults(silent=True)
  492. # ###########################################################################################################
  493. # ############################################ Data #########################################################
  494. # ###########################################################################################################
  495. self.recent = []
  496. self.recent_projects = []
  497. self.clipboard = QtWidgets.QApplication.clipboard()
  498. self.project_filename = None
  499. self.toggle_units_ignore = False
  500. # ###########################################################################################################
  501. # ########################################## LOAD LANGUAGES ################################################
  502. # ###########################################################################################################
  503. self.languages = fcTranslate.load_languages()
  504. for name in sorted(self.languages.values()):
  505. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  506. # ###########################################################################################################
  507. # ####################################### APPLY APP LANGUAGE ################################################
  508. # ###########################################################################################################
  509. ret_val = fcTranslate.apply_language('strings')
  510. if ret_val == "no language":
  511. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  512. log.debug("Could not find the Language files. The App strings are missing.")
  513. else:
  514. # make the current language the current selection on the language combobox
  515. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  516. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  517. # ###########################################################################################################
  518. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  519. # ###########################################################################################################
  520. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  521. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  522. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  523. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  524. self.defaults.propagate_defaults()
  525. # ###########################################################################################################
  526. # ######################################## UPDATE THE OPTIONS ###############################################
  527. # ###########################################################################################################
  528. self.options = LoudDict()
  529. # -----------------------------------------------------------------------------------------------------------
  530. # Update the self.options from the self.defaults
  531. # The self.defaults holds the application defaults while the self.options holds the object defaults
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Copy app defaults to project options
  534. for def_key, def_val in self.defaults.items():
  535. self.options[def_key] = deepcopy(def_val)
  536. self.preferencesUiManager.show_preferences_gui()
  537. # ### End of Data ####
  538. # ###########################################################################################################
  539. # #################################### SETUP OBJECT COLLECTION ##############################################
  540. # ###########################################################################################################
  541. self.collection = ObjectCollection(self)
  542. self.ui.project_tab_layout.addWidget(self.collection.view)
  543. # ### Adjust tabs width ## ##
  544. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  545. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  546. self.collection.view.setMinimumWidth(290)
  547. self.log.debug("Finished creating Object Collection.")
  548. # ###########################################################################################################
  549. # ######################################## SETUP Plot Area ##################################################
  550. # ###########################################################################################################
  551. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  552. if self.defaults["global_graphic_engine"] == '3D':
  553. self.is_legacy = False
  554. else:
  555. self.is_legacy = True
  556. # Event signals disconnect id holders
  557. self.mp = None
  558. self.mm = None
  559. self.mr = None
  560. self.mdc = None
  561. self.mp_zc = None
  562. self.kp = None
  563. # Matplotlib axis
  564. self.axes = None
  565. if show_splash:
  566. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  567. "Canvas initialization started."),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. start_plot_time = time.time() # debug
  571. self.plotcanvas = None
  572. self.app_cursor = None
  573. self.hover_shapes = None
  574. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  575. # setup the PlotCanvas
  576. self.on_plotcanvas_setup()
  577. end_plot_time = time.time()
  578. self.used_time = end_plot_time - start_plot_time
  579. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  580. if show_splash:
  581. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  582. "Canvas initialization started.\n"
  583. "Canvas initialization finished in"), '%.2f' % self.used_time),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. self.ui.splitter.setStretchFactor(1, 2)
  587. # ###########################################################################################################
  588. # ############################################### SYS TRAY ##################################################
  589. # ###########################################################################################################
  590. if self.defaults["global_systray_icon"]:
  591. self.parent_w = QtWidgets.QWidget()
  592. if self.cmd_line_headless == 1:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. headless=True,
  597. parent=self.parent_w)
  598. else:
  599. self.trayIcon = FlatCAMSystemTray(app=self,
  600. icon=QtGui.QIcon(self.resource_location +
  601. '/flatcam_icon32_green.png'),
  602. parent=self.parent_w)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ###########################################
  614. # ###########################################################################################################
  615. self.activity_view = FlatCAMActivityView(app=self)
  616. self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  618. # ###########################################################################################################
  619. # ############################################# Signal handling #############################################
  620. # ###########################################################################################################
  621. # ########################################## Custom signals ################################################
  622. # signal for displaying messages in status bar
  623. self.inform.connect(self.info)
  624. # signal to be called when the app is quiting
  625. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  626. self.message.connect(self.message_dialog)
  627. # self.progress.connect(self.set_progress_bar)
  628. # signals that are emitted when object state changes
  629. self.object_created.connect(self.on_object_created)
  630. self.object_changed.connect(self.on_object_changed)
  631. self.object_plotted.connect(self.on_object_plotted)
  632. self.plots_updated.connect(self.on_plots_updated)
  633. # signals emitted when file state change
  634. self.file_opened.connect(self.register_recent)
  635. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  636. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  637. # ########################################## Standard signals ###############################################
  638. # ### Menu
  639. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  640. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  641. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  642. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  643. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  644. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  645. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  646. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  647. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  648. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  649. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  650. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  651. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  652. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  653. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  654. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  655. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  656. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  657. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  658. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  659. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  660. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  661. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  662. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  663. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  664. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  665. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  666. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  667. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  668. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  669. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  670. self.ui.menufile_exit.triggered.connect(self.final_save)
  671. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  672. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  673. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  674. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  675. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  676. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  677. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  678. self.ui.menueditdelete.triggered.connect(self.on_delete)
  679. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  680. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  681. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  682. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  683. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  684. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  685. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  686. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  687. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  688. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  689. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  690. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  691. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  692. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  693. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  694. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  695. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  696. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  697. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  698. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  699. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  700. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  701. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  702. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  703. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  704. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  705. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  706. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  707. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  708. self.ui.menuview_replot.triggered.connect(self.plot_all)
  709. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  710. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  711. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  712. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  713. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  714. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  715. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  716. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  717. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  718. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  719. self.ui.menuhelp_about.triggered.connect(self.on_about)
  720. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  721. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  722. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  723. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  724. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  725. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  726. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  727. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  728. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  729. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  730. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  731. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  732. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  733. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  734. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  735. # ToolBar signals
  736. self.connect_toolbar_signals()
  737. # Notebook and Plot Tab Area signals
  738. # make the right click on the notebook tab and plot tab area tab raise a menu
  739. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  740. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  741. self.on_tab_setup_context_menu()
  742. # activate initial state
  743. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  744. # Context Menu
  745. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  746. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  747. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  748. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  749. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  750. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  751. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  752. self.ui.clearplot.triggered.connect(self.clear_plots)
  753. self.ui.replot.triggered.connect(self.plot_all)
  754. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  755. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  756. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  757. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  758. self.ui.popmenu_move.triggered.connect(self.obj_move)
  759. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  760. # Project Context Menu -> Color Setting
  761. for act in self.ui.menuprojectcolor.actions():
  762. act.triggered.connect(self.on_set_color_action_triggered)
  763. # ###########################################################################################################
  764. # #################################### GUI PREFERENCES SIGNALS ##############################################
  765. # ###########################################################################################################
  766. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  767. lambda: self.on_toggle_units(no_pref=False))
  768. # ##################################### Workspace Setting Signals ###########################################
  769. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  770. self.on_workspace_modified)
  771. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  772. self.on_workspace_modified
  773. )
  774. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  775. # ###########################################################################################################
  776. # ######################################## GUI SETTINGS SIGNALS #############################################
  777. # ###########################################################################################################
  778. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  779. # ######################################## Tools related signals ############################################
  780. # Film Tool
  781. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  782. self.on_film_color_entry)
  783. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  784. self.on_film_color_button)
  785. # QRCode Tool
  786. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  787. self.on_qrcode_fill_color_entry)
  788. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  789. self.on_qrcode_fill_color_button)
  790. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  791. self.on_qrcode_back_color_entry)
  792. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  793. self.on_qrcode_back_color_button)
  794. # portability changed signal
  795. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  796. # Object list
  797. self.collection.view.activated.connect(self.on_row_activated)
  798. self.collection.item_selected.connect(self.on_row_selected)
  799. self.object_status_changed.connect(self.on_collection_updated)
  800. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  801. # Export Excellon parameters.
  802. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  803. self.on_update_exc_export
  804. )
  805. # call it once to make sure it is updated at startup
  806. self.on_update_exc_export(state=self.defaults["excellon_update"])
  807. # when there are arguments at application startup this get launched
  808. self.args_at_startup[list].connect(self.on_startup_args)
  809. # ###########################################################################################################
  810. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  811. # ###########################################################################################################
  812. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  813. lambda: self.restore_extensions(ext_type='excellon'))
  814. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  815. lambda: self.restore_extensions(ext_type='gcode'))
  816. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  817. lambda: self.restore_extensions(ext_type='gerber'))
  818. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  819. lambda: self.delete_all_extensions(ext_type='excellon'))
  820. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  821. lambda: self.delete_all_extensions(ext_type='gcode'))
  822. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  823. lambda: self.delete_all_extensions(ext_type='gerber'))
  824. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  825. lambda: self.add_extension(ext_type='excellon'))
  826. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  827. lambda: self.add_extension(ext_type='gcode'))
  828. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  829. lambda: self.add_extension(ext_type='gerber'))
  830. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  831. lambda: self.del_extension(ext_type='excellon'))
  832. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  833. lambda: self.del_extension(ext_type='gcode'))
  834. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  835. lambda: self.del_extension(ext_type='gerber'))
  836. # connect the 'Apply' buttons from the Preferences/File Associations
  837. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  838. lambda: self.on_register_files(obj_type='excellon'))
  839. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  840. lambda: self.on_register_files(obj_type='gcode'))
  841. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  842. lambda: self.on_register_files(obj_type='gerber'))
  843. # ###########################################################################################################
  844. # ########################################### KEYWORDS SIGNALS ##############################################
  845. # ###########################################################################################################
  846. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  847. lambda: self.restore_extensions(ext_type='keyword'))
  848. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  849. lambda: self.delete_all_extensions(ext_type='keyword'))
  850. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  851. lambda: self.add_extension(ext_type='keyword'))
  852. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  853. lambda: self.del_extension(ext_type='keyword'))
  854. # connect the abort_all_tasks related slots to the related signals
  855. self.proc_container.idle_flag.connect(self.app_is_idle)
  856. # signal emitted when a tab is closed in the Plot Area
  857. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  858. # signal to close the application
  859. self.close_app_signal.connect(self.kill_app)
  860. # ################################# FINISHED CONNECTING SIGNALS #############################################
  861. # ###########################################################################################################
  862. # ###########################################################################################################
  863. # ###########################################################################################################
  864. self.log.debug("Finished connecting Signals.")
  865. # ###########################################################################################################
  866. # ########################################## Other setups ###################################################
  867. # ###########################################################################################################
  868. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  869. # depending on from where those tools are called different actions can be done
  870. self.call_source = 'app'
  871. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  872. self.tool_tab_locked = False
  873. # decide if to show or hide the Notebook side of the screen at startup
  874. if self.defaults["global_project_at_startup"] is True:
  875. self.ui.splitter.setSizes([1, 1])
  876. else:
  877. self.ui.splitter.setSizes([0, 1])
  878. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  879. self.setup_component_editor()
  880. # ###########################################################################################################
  881. # ####################################### Auto-complete KEYWORDS ############################################
  882. # ###########################################################################################################
  883. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  884. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  885. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  886. 'export_exc',
  887. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  888. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  889. 'interiors', 'isolate', 'join_excellon',
  890. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  891. 'mirror', 'ncc',
  892. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  893. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  894. 'options', 'origin',
  895. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  896. 'save', 'save_project',
  897. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  898. 'skew', 'subtract_poly', 'subtract_rectangle',
  899. 'version', 'write_gcode'
  900. ]
  901. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  902. 'Paste_1',
  903. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  904. 'Toolchange_manual', 'True', 'Users',
  905. 'all', 'auto', 'axis',
  906. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  907. 'contour', 'default',
  908. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  909. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  910. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  911. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  912. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  913. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  914. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  915. 'spacing_columns',
  916. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  917. 'toolchange_xy', 'toolchangez', 'travelz',
  918. 'tooldia', 'use_threads', 'value',
  919. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  920. ]
  921. self.tcl_keywords = [
  922. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  923. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  924. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  925. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  926. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  927. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  928. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  929. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  930. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  931. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  932. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  933. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  934. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  935. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  936. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  937. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  938. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  939. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  940. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  941. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  942. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  943. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  944. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  945. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  946. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  947. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  948. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  949. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  950. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  951. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  952. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  953. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  954. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  955. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  956. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  957. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  958. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  959. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  960. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  961. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  962. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  963. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  964. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  965. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  966. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  967. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  968. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  969. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  970. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  971. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  972. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  973. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  974. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  975. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  976. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  977. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  978. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  979. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  980. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  981. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  982. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  983. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  984. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  985. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  986. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  987. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  988. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  989. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  990. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  991. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  992. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  993. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  994. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  995. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  996. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  997. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  998. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  999. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1000. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1001. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1002. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1003. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1004. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1005. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1006. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1007. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1008. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1009. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1010. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1011. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1012. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1013. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1014. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1015. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1016. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1017. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1018. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1019. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1020. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1021. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1022. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1023. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1024. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1025. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1026. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1027. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1028. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1029. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1030. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1031. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1032. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1033. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1034. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1035. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1036. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1037. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1038. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1039. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1040. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1041. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1042. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1043. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1044. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1045. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1046. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1047. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1048. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1049. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1050. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1051. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1052. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1053. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1054. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1055. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1056. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1057. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1058. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1059. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1060. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1061. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1062. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1063. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1064. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1065. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1066. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1067. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1068. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1069. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1070. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1071. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1072. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1073. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1074. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1075. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1076. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1077. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1078. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1079. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1080. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1081. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1082. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1083. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1084. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1085. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1086. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1087. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1088. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1089. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1090. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1091. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1092. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1093. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1094. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1095. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1096. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1097. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1098. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1099. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1100. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1101. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1102. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1103. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1104. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1105. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1106. ]
  1107. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1108. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1109. # ###########################################################################################################
  1110. # ############################################## Shell SETUP ################################################
  1111. # ###########################################################################################################
  1112. self.shell = FCShell(app=self, version=self.version)
  1113. self.ui.shell_dock.setWidget(self.shell)
  1114. self.log.debug("TCL Shell has been initialized.")
  1115. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1116. if self.defaults["global_shell_at_startup"]:
  1117. self.ui.shell_dock.show()
  1118. else:
  1119. self.ui.shell_dock.hide()
  1120. # ###########################################################################################################
  1121. # ########################################## Tools and Plugins ##############################################
  1122. # ###########################################################################################################
  1123. self.dblsidedtool = None
  1124. self.distance_tool = None
  1125. self.distance_min_tool = None
  1126. self.panelize_tool = None
  1127. self.film_tool = None
  1128. self.paste_tool = None
  1129. self.calculator_tool = None
  1130. self.rules_tool = None
  1131. self.sub_tool = None
  1132. self.move_tool = None
  1133. self.cutout_tool = None
  1134. self.ncclear_tool = None
  1135. self.optimal_tool = None
  1136. self.paint_tool = None
  1137. self.transform_tool = None
  1138. self.properties_tool = None
  1139. self.pdf_tool = None
  1140. self.image_tool = None
  1141. self.pcb_wizard_tool = None
  1142. self.cal_exc_tool = None
  1143. self.qrcode_tool = None
  1144. self.copper_thieving_tool = None
  1145. self.fiducial_tool = None
  1146. self.edrills_tool = None
  1147. self.align_objects_tool = None
  1148. self.punch_tool = None
  1149. self.invert_tool = None
  1150. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1151. try:
  1152. self.install_tools()
  1153. except AttributeError as e:
  1154. log.debug("App.__init__() install tools() --> %s" % str(e))
  1155. # ###########################################################################################################
  1156. # ############################################ SETUP RECENT ITEMS ###########################################
  1157. # ###########################################################################################################
  1158. self.setup_recent_items()
  1159. # ###########################################################################################################
  1160. # ######################################### BookMarks Manager ###############################################
  1161. # ###########################################################################################################
  1162. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1163. self.install_bookmarks()
  1164. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1165. # ###########################################################################################################
  1166. # ########################################### Tools Database ################################################
  1167. # ###########################################################################################################
  1168. self.tools_db_tab = None
  1169. # ### System Font Parsing ###
  1170. # self.f_parse = ParseFont(self)
  1171. # self.parse_system_fonts()
  1172. # ###########################################################################################################
  1173. # ######################################### Check for updates ###############################################
  1174. # ###########################################################################################################
  1175. # Separate thread (Not worker)
  1176. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1177. if (self.beta is False or self.beta is None) and \
  1178. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1179. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1180. # self.thr2 = QtCore.QThread()
  1181. self.worker_task.emit({'fcn': self.version_check,
  1182. 'params': []})
  1183. # self.thr2.start(QtCore.QThread.LowPriority)
  1184. # ###########################################################################################################
  1185. # ##################################### Register files with FlatCAM; #######################################
  1186. # ################################### It works only for Windows for now ####################################
  1187. # ###########################################################################################################
  1188. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1189. self.on_register_files()
  1190. # ###########################################################################################################
  1191. # ######################################## Variables for global usage #######################################
  1192. # ###########################################################################################################
  1193. # hold the App units
  1194. self.units = 'MM'
  1195. # coordinates for relative position display
  1196. self.rel_point1 = (0, 0)
  1197. self.rel_point2 = (0, 0)
  1198. # variable to store coordinates
  1199. self.pos = (0, 0)
  1200. self.pos_canvas = (0, 0)
  1201. self.pos_jump = (0, 0)
  1202. # variable to store mouse coordinates
  1203. self.mouse = [0, 0]
  1204. # variable to store the delta positions on cavnas
  1205. self.dx = 0
  1206. self.dy = 0
  1207. # decide if we have a double click or single click
  1208. self.doubleclick = False
  1209. # store here the is_dragging value
  1210. self.event_is_dragging = False
  1211. # variable to store if a command is active (then the var is not None) and which one it is
  1212. self.command_active = None
  1213. # variable to store the status of moving selection action
  1214. # None value means that it's not an selection action
  1215. # True value = a selection from left to right
  1216. # False value = a selection from right to left
  1217. self.selection_type = None
  1218. # List to store the objects that are currently loaded in FlatCAM
  1219. # This list is updated on each object creation or object delete
  1220. self.all_objects_list = []
  1221. self.objects_under_the_click_list = []
  1222. # List to store the objects that are selected
  1223. self.sel_objects_list = []
  1224. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1225. self.key_modifiers = None
  1226. # Variable to hold the status of the axis
  1227. self.toggle_axis = True
  1228. # Variable to hold the status of the grid lines
  1229. self.toggle_grid_lines = True
  1230. # Variable to store the status of the fullscreen event
  1231. self.toggle_fscreen = False
  1232. # Variable to store the status of the code editor
  1233. self.toggle_codeeditor = False
  1234. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1235. self.click_noproject = False
  1236. self.cursor = None
  1237. # Variable to store the GCODE that was edited
  1238. self.gcode_edited = ""
  1239. self.text_editor_tab = None
  1240. # reference for the self.ui.code_editor
  1241. self.reference_code_editor = None
  1242. self.script_code = ''
  1243. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1244. self.tools_db_changed_flag = False
  1245. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1246. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1247. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1248. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1249. 'tsm']
  1250. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1251. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1252. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1253. 'sbp', 'tap', 'xpi']
  1254. self.svg_list = ['svg']
  1255. self.dxf_list = ['dxf']
  1256. self.pdf_list = ['pdf']
  1257. self.prj_list = ['flatprj']
  1258. self.conf_list = ['flatconfig']
  1259. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1260. # flag for polygons not cleared
  1261. self.poly_not_cleared = False
  1262. # VisPy visuals
  1263. self.isHovering = False
  1264. self.notHovering = True
  1265. # Window geometry
  1266. self.x_pos = None
  1267. self.y_pos = None
  1268. self.width = None
  1269. self.height = None
  1270. # when True, the app has to return from any thread
  1271. self.abort_flag = False
  1272. # set the value used in the Windows Title
  1273. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1274. # this holds a widget that is installed in the Plot Area when View Source option is used
  1275. self.source_editor_tab = None
  1276. self.pagesize = {}
  1277. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1278. # VisPy visuals
  1279. if self.is_legacy is False:
  1280. try:
  1281. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1282. except AttributeError:
  1283. self.tool_shapes = None
  1284. else:
  1285. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1286. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1287. # used in the delayed shutdown self.start_delayed_quit() method
  1288. self.save_timer = None
  1289. # ###########################################################################################################
  1290. # ################################## ADDING FlatCAM EDITORS section #########################################
  1291. # ###########################################################################################################
  1292. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1293. # at the first launch of the App , the editors will not be functional.
  1294. try:
  1295. self.geo_editor = FlatCAMGeoEditor(self)
  1296. except AttributeError:
  1297. pass
  1298. try:
  1299. self.exc_editor = FlatCAMExcEditor(self)
  1300. except AttributeError:
  1301. pass
  1302. try:
  1303. self.grb_editor = FlatCAMGrbEditor(self)
  1304. except AttributeError:
  1305. pass
  1306. self.log.debug("Finished adding FlatCAM Editor's.")
  1307. self.set_ui_title(name=_("New Project - Not saved"))
  1308. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1309. current_platform = platform.architecture()[0]
  1310. if current_platform != '64bit':
  1311. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1312. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1313. # ###########################################################################################################
  1314. # ########################################### EXCLUSION AREAS ###############################################
  1315. # ###########################################################################################################
  1316. self.exc_areas = ExclusionAreas(app=self)
  1317. # ###########################################################################################################
  1318. # ##################################### Finished the CONSTRUCTOR ############################################
  1319. # ###########################################################################################################
  1320. App.log.debug("END of constructor. Releasing control.")
  1321. # ###########################################################################################################
  1322. # ########################################## SHOW GUI #######################################################
  1323. # ###########################################################################################################
  1324. # if the app is not started as headless, show it
  1325. if self.cmd_line_headless != 1:
  1326. if show_splash:
  1327. # finish the splash
  1328. self.splash.finish(self.ui)
  1329. mgui_settings = QSettings("Open Source", "FlatCAM")
  1330. if mgui_settings.contains("maximized_gui"):
  1331. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1332. if maximized_ui is True:
  1333. self.ui.showMaximized()
  1334. else:
  1335. self.ui.show()
  1336. else:
  1337. self.ui.show()
  1338. if self.defaults["global_systray_icon"]:
  1339. self.trayIcon.show()
  1340. else:
  1341. log.warning("******************* RUNNING HEADLESS *******************")
  1342. # ###########################################################################################################
  1343. # ######################################## START-UP ARGUMENTS ###############################################
  1344. # ###########################################################################################################
  1345. # test if the program was started with a script as parameter
  1346. if self.cmd_line_shellvar:
  1347. try:
  1348. cnt = 0
  1349. command_tcl = 0
  1350. for i in self.cmd_line_shellvar.split(','):
  1351. if i is not None:
  1352. # noinspection PyBroadException
  1353. try:
  1354. command_tcl = eval(i)
  1355. except Exception:
  1356. command_tcl = i
  1357. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1358. cnt += 1
  1359. # if there are Windows paths then replace the path separator with a Unix like one
  1360. if sys.platform == 'win32':
  1361. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1362. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1363. except Exception as ext:
  1364. print("ERROR: ", ext)
  1365. sys.exit(2)
  1366. if self.cmd_line_shellfile:
  1367. if self.cmd_line_headless != 1:
  1368. if self.ui.shell_dock.isHidden():
  1369. self.ui.shell_dock.show()
  1370. try:
  1371. with open(self.cmd_line_shellfile, "r") as myfile:
  1372. # if show_splash:
  1373. # self.splash.showMessage('%s: %ssec\n%s' % (
  1374. # _("Canvas initialization started.\n"
  1375. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1376. # _("Executing Tcl Script ...")),
  1377. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1378. # color=QtGui.QColor("gray"))
  1379. cmd_line_shellfile_text = myfile.read()
  1380. if self.cmd_line_headless != 1:
  1381. self.shell.exec_command(cmd_line_shellfile_text)
  1382. else:
  1383. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1384. except Exception as ext:
  1385. print("ERROR: ", ext)
  1386. sys.exit(2)
  1387. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1388. # the path/file_name must be enclosed in quotes if it contain spaces
  1389. if App.args:
  1390. self.args_at_startup.emit(App.args)
  1391. if self.defaults.old_defaults_found is True:
  1392. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1393. "Please reboot the application to update."))
  1394. self.defaults.old_defaults_found = False
  1395. # ######################################### INIT FINISHED #######################################################
  1396. # #################################################################################################################
  1397. # #################################################################################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. @staticmethod
  1402. def copy_and_overwrite(from_path, to_path):
  1403. """
  1404. From here:
  1405. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1406. :param from_path: source path
  1407. :param to_path: destination path
  1408. :return: None
  1409. """
  1410. if os.path.exists(to_path):
  1411. shutil.rmtree(to_path)
  1412. try:
  1413. shutil.copytree(from_path, to_path)
  1414. except FileNotFoundError:
  1415. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1416. shutil.copytree(from_new_path, to_path)
  1417. def on_startup_args(self, args, silent=False):
  1418. """
  1419. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1420. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1421. :param args: a list containing the application args at startup
  1422. :return: None
  1423. """
  1424. if args is not None:
  1425. args_to_process = args
  1426. else:
  1427. args_to_process = App.args
  1428. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1429. for argument in args_to_process:
  1430. if '.FlatPrj'.lower() in argument.lower():
  1431. try:
  1432. project_name = str(argument)
  1433. if project_name == "":
  1434. if silent is False:
  1435. self.inform.emit(_("Cancelled."))
  1436. else:
  1437. # self.open_project(project_name)
  1438. run_from_arg = True
  1439. # self.worker_task.emit({'fcn': self.open_project,
  1440. # 'params': [project_name, run_from_arg]})
  1441. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1442. except Exception as e:
  1443. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1444. elif '.FlatConfig'.lower() in argument.lower():
  1445. try:
  1446. file_name = str(argument)
  1447. if file_name == "":
  1448. if silent is False:
  1449. self.inform.emit(_("Open Config file failed."))
  1450. else:
  1451. run_from_arg = True
  1452. # self.worker_task.emit({'fcn': self.open_config_file,
  1453. # 'params': [file_name, run_from_arg]})
  1454. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1455. except Exception as e:
  1456. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1457. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1458. try:
  1459. file_name = str(argument)
  1460. if file_name == "":
  1461. if silent is False:
  1462. self.inform.emit(_("Open Script file failed."))
  1463. else:
  1464. if silent is False:
  1465. self.on_fileopenscript(name=file_name)
  1466. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1467. self.on_filerunscript(name=file_name)
  1468. except Exception as e:
  1469. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1470. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1471. log.debug("App.on_startup_args() --> Quit event.")
  1472. sys.exit()
  1473. elif 'save'.lower() in argument.lower():
  1474. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1475. self.preferencesUiManager.save_defaults()
  1476. else:
  1477. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1478. proc_arg = argument.lower()
  1479. for ext in exc_list:
  1480. proc_ext = ext.replace(' ', '')
  1481. proc_ext = '.%s' % proc_ext
  1482. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1483. file_name = str(argument)
  1484. if file_name == "":
  1485. if silent is False:
  1486. self.inform.emit(_("Open Excellon file failed."))
  1487. else:
  1488. self.on_fileopenexcellon(name=file_name, signal=None)
  1489. return
  1490. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1491. for ext in gco_list:
  1492. proc_ext = ext.replace(' ', '')
  1493. proc_ext = '.%s' % proc_ext
  1494. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1495. file_name = str(argument)
  1496. if file_name == "":
  1497. if silent is False:
  1498. self.inform.emit(_("Open GCode file failed."))
  1499. else:
  1500. self.on_fileopengcode(name=file_name, signal=None)
  1501. return
  1502. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1503. for ext in grb_list:
  1504. proc_ext = ext.replace(' ', '')
  1505. proc_ext = '.%s' % proc_ext
  1506. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1507. file_name = str(argument)
  1508. if file_name == "":
  1509. if silent is False:
  1510. self.inform.emit(_("Open Gerber file failed."))
  1511. else:
  1512. self.on_fileopengerber(name=file_name, signal=None)
  1513. return
  1514. # if it reached here without already returning then the app was registered with a file that it does not
  1515. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1516. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1517. # for arg in args_to_process:
  1518. # if 'FlatCAM.exe' in arg:
  1519. # continue
  1520. # else:
  1521. # sys.exit(2)
  1522. def set_ui_title(self, name):
  1523. """
  1524. Sets the title of the main window.
  1525. :param name: String that store the project path and project name
  1526. :return: None
  1527. """
  1528. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1529. (self.version,
  1530. ('BETA' if self.beta else ''),
  1531. platform.architecture()[0],
  1532. self.engine,
  1533. name)
  1534. )
  1535. def on_app_restart(self):
  1536. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1537. # be left in the SySTray
  1538. try:
  1539. self.trayIcon.hide()
  1540. except Exception:
  1541. pass
  1542. fcTranslate.restart_program(app=self)
  1543. def clear_pool(self):
  1544. """
  1545. Clear the multiprocessing pool and calls garbage collector.
  1546. :return: None
  1547. """
  1548. self.pool.close()
  1549. self.pool = Pool()
  1550. self.pool_recreated.emit(self.pool)
  1551. gc.collect()
  1552. def install_tools(self):
  1553. """
  1554. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1555. Instantiation of the Tools classes.
  1556. The order that the tools are installed is important as they can depend on each other install position.
  1557. :return: None
  1558. """
  1559. self.distance_tool = Distance(self)
  1560. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1561. before=self.ui.menueditorigin,
  1562. separator=False)
  1563. self.distance_min_tool = DistanceMin(self)
  1564. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1565. pos=self.ui.menuedit,
  1566. before=self.ui.menueditorigin,
  1567. separator=True)
  1568. self.dblsidedtool = DblSidedTool(self)
  1569. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1570. self.cal_exc_tool = ToolCalibration(self)
  1571. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1572. before=self.dblsidedtool.menuAction,
  1573. separator=False)
  1574. self.align_objects_tool = AlignObjects(self)
  1575. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1576. self.edrills_tool = ToolExtractDrills(self)
  1577. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1578. self.panelize_tool = Panelize(self)
  1579. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1580. self.film_tool = Film(self)
  1581. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1582. self.paste_tool = SolderPaste(self)
  1583. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1584. self.calculator_tool = ToolCalculator(self)
  1585. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1586. self.sub_tool = ToolSub(self)
  1587. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1588. pos=self.ui.menutool, separator=True)
  1589. self.rules_tool = RulesCheck(self)
  1590. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1591. pos=self.ui.menutool, separator=False)
  1592. self.optimal_tool = ToolOptimal(self)
  1593. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1594. pos=self.ui.menutool, separator=True)
  1595. self.move_tool = ToolMove(self)
  1596. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1597. before=self.ui.menueditorigin, separator=True)
  1598. self.cutout_tool = CutOut(self)
  1599. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1600. before=self.sub_tool.menuAction)
  1601. self.ncclear_tool = NonCopperClear(self)
  1602. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1603. before=self.sub_tool.menuAction, separator=True)
  1604. self.paint_tool = ToolPaint(self)
  1605. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1606. before=self.sub_tool.menuAction, separator=True)
  1607. self.copper_thieving_tool = ToolCopperThieving(self)
  1608. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1609. pos=self.ui.menutool)
  1610. self.fiducial_tool = ToolFiducials(self)
  1611. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1612. pos=self.ui.menutool)
  1613. self.qrcode_tool = QRCode(self)
  1614. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1615. pos=self.ui.menutool)
  1616. self.punch_tool = ToolPunchGerber(self)
  1617. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1618. self.invert_tool = ToolInvertGerber(self)
  1619. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1620. self.transform_tool = ToolTransform(self)
  1621. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1622. pos=self.ui.menuoptions, separator=True)
  1623. self.properties_tool = Properties(self)
  1624. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1625. pos=self.ui.menuoptions)
  1626. self.pdf_tool = ToolPDF(self)
  1627. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1628. pos=self.ui.menufileimport,
  1629. separator=True)
  1630. self.image_tool = ToolImage(self)
  1631. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1632. pos=self.ui.menufileimport,
  1633. separator=True)
  1634. self.pcb_wizard_tool = PcbWizard(self)
  1635. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1636. pos=self.ui.menufileimport)
  1637. self.log.debug("Tools are installed.")
  1638. def remove_tools(self):
  1639. """
  1640. Will remove all the actions in the Tool menu.
  1641. :return: None
  1642. """
  1643. for act in self.ui.menutool.actions():
  1644. self.ui.menutool.removeAction(act)
  1645. def init_tools(self):
  1646. """
  1647. Initialize the Tool tab in the notebook side of the central widget.
  1648. Remove the actions in the Tools menu.
  1649. Instantiate again the FlatCAM tools (plugins).
  1650. All this is required when changing the layout: standard, compact etc.
  1651. :return: None
  1652. """
  1653. log.debug("init_tools()")
  1654. # delete the data currently in the Tools Tab and the Tab itself
  1655. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1656. if widget is not None:
  1657. widget.deleteLater()
  1658. self.ui.notebook.removeTab(2)
  1659. # rebuild the Tools Tab
  1660. self.ui.tool_tab = QtWidgets.QWidget()
  1661. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1662. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1663. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1664. self.ui.tool_scroll_area = VerticalScrollArea()
  1665. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1666. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1667. # first remove all of them
  1668. self.remove_tools()
  1669. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1670. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1671. '&Command Line\tS')
  1672. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1673. # third install all of them
  1674. try:
  1675. self.install_tools()
  1676. except AttributeError:
  1677. pass
  1678. self.log.debug("Tools are initialized.")
  1679. # def parse_system_fonts(self):
  1680. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1681. # 'params': []})
  1682. def connect_toolbar_signals(self):
  1683. """
  1684. Reconnect the signals to the actions in the toolbar.
  1685. This has to be done each time after the FlatCAM tools are removed/installed.
  1686. :return: None
  1687. """
  1688. # Toolbar
  1689. # File Toolbar Signals
  1690. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1691. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1692. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1693. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1694. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1695. # View Toolbar Signals
  1696. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1697. self.ui.replot_btn.triggered.connect(self.plot_all)
  1698. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1699. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1700. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1701. # Edit Toolbar Signals
  1702. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1703. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1704. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1705. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1706. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1707. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1708. self.ui.delete_btn.triggered.connect(self.on_delete)
  1709. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1710. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1711. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1712. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1713. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1714. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1715. # Scripting Toolbar Signals
  1716. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1717. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1718. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1719. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1720. # Tools Toolbar Signals
  1721. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1722. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1723. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1724. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1725. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1726. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1727. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1728. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1729. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1730. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1731. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1732. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1733. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1734. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1735. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1736. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1737. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1738. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1739. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1740. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1741. def object2editor(self):
  1742. """
  1743. Send the current Geometry or Excellon object (if any) into the it's editor.
  1744. :return: None
  1745. """
  1746. self.defaults.report_usage("object2editor()")
  1747. # disable the objects menu as it may interfere with the Editors
  1748. self.ui.menuobjects.setDisabled(True)
  1749. edited_object = self.collection.get_active()
  1750. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1751. isinstance(edited_object, ExcellonObject):
  1752. pass
  1753. else:
  1754. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1755. return
  1756. if isinstance(edited_object, GeometryObject):
  1757. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1758. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1759. # we set the notebook to hidden
  1760. # self.ui.splitter.setSizes([0, 1])
  1761. if edited_object.multigeo is True:
  1762. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1763. if len(sel_rows) > 1:
  1764. self.inform.emit('[WARNING_NOTCL] %s' %
  1765. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1766. "is not possible.\n"
  1767. "Edit only one geometry at a time."))
  1768. # determine the tool dia of the selected tool
  1769. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1770. # now find the key in the edited_object.tools that has this tooldia
  1771. multi_tool = 1
  1772. for tool in edited_object.tools:
  1773. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1774. multi_tool = tool
  1775. break
  1776. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1777. else:
  1778. self.geo_editor.edit_fcgeometry(edited_object)
  1779. # set call source to the Editor we go into
  1780. self.call_source = 'geo_editor'
  1781. elif isinstance(edited_object, ExcellonObject):
  1782. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1783. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1784. if self.ui.splitter.sizes()[0] == 0:
  1785. self.ui.splitter.setSizes([1, 1])
  1786. self.exc_editor.edit_fcexcellon(edited_object)
  1787. # set call source to the Editor we go into
  1788. self.call_source = 'exc_editor'
  1789. elif isinstance(edited_object, GerberObject):
  1790. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1791. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1792. if self.ui.splitter.sizes()[0] == 0:
  1793. self.ui.splitter.setSizes([1, 1])
  1794. self.grb_editor.edit_fcgerber(edited_object)
  1795. # set call source to the Editor we go into
  1796. self.call_source = 'grb_editor'
  1797. # reset the following variables so the UI is built again after edit
  1798. edited_object.ui_build = False
  1799. edited_object.build_aperture_storage = False
  1800. # make sure that we can't select another object while in Editor Mode:
  1801. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1802. self.ui.project_frame.setDisabled(True)
  1803. # delete any selection shape that might be active as they are not relevant in Editor
  1804. self.delete_selection_shape()
  1805. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1806. self.ui.plot_tab_area.protectTab(0)
  1807. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1808. self.should_we_save = True
  1809. def editor2object(self, cleanup=None):
  1810. """
  1811. Transfers the Geometry or Excellon from it's editor to the current object.
  1812. :return: None
  1813. """
  1814. self.defaults.report_usage("editor2object()")
  1815. # re-enable the objects menu that was disabled on entry in Editor mode
  1816. self.ui.menuobjects.setDisabled(False)
  1817. # do not update a geometry or excellon object unless it comes out of an editor
  1818. if self.call_source != 'app':
  1819. edited_obj = self.collection.get_active()
  1820. if cleanup is None:
  1821. msgbox = QtWidgets.QMessageBox()
  1822. msgbox.setText(_("Do you want to save the edited object?"))
  1823. msgbox.setWindowTitle(_("Close Editor"))
  1824. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1825. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1826. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1827. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1828. msgbox.setDefaultButton(bt_yes)
  1829. msgbox.exec_()
  1830. response = msgbox.clickedButton()
  1831. if response == bt_yes:
  1832. # clean the Tools Tab
  1833. self.ui.tool_scroll_area.takeWidget()
  1834. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1835. self.ui.notebook.setTabText(2, "Tool")
  1836. if isinstance(edited_obj, GeometryObject):
  1837. obj_type = "Geometry"
  1838. if cleanup is None:
  1839. self.geo_editor.update_fcgeometry(edited_obj)
  1840. # self.geo_editor.update_options(edited_obj)
  1841. self.geo_editor.deactivate()
  1842. # restore GUI to the Selected TAB
  1843. # Remove anything else in the GUI
  1844. self.ui.tool_scroll_area.takeWidget()
  1845. # update the geo object options so it is including the bounding box values
  1846. try:
  1847. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1848. edited_obj.options['xmin'] = xmin
  1849. edited_obj.options['ymin'] = ymin
  1850. edited_obj.options['xmax'] = xmax
  1851. edited_obj.options['ymax'] = ymax
  1852. except AttributeError as e:
  1853. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1854. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1855. edited_obj.build_ui()
  1856. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1857. elif isinstance(edited_obj, GerberObject):
  1858. obj_type = "Gerber"
  1859. if cleanup is None:
  1860. self.grb_editor.update_fcgerber()
  1861. self.grb_editor.update_options(edited_obj)
  1862. self.grb_editor.deactivate_grb_editor()
  1863. # delete the old object (the source object) if it was an empty one
  1864. try:
  1865. if len(edited_obj.solid_geometry) == 0:
  1866. old_name = edited_obj.options['name']
  1867. self.collection.set_active(old_name)
  1868. self.collection.delete_active()
  1869. except TypeError:
  1870. # if the solid_geometry is a single Polygon the len() will not work
  1871. # in any case, falling here means that we have something in the solid_geometry, even if only
  1872. # a single Polygon, therefore we pass this
  1873. pass
  1874. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1875. # restore GUI to the Selected TAB
  1876. # Remove anything else in the GUI
  1877. self.ui.selected_scroll_area.takeWidget()
  1878. elif isinstance(edited_obj, ExcellonObject):
  1879. obj_type = "Excellon"
  1880. if cleanup is None:
  1881. self.exc_editor.update_fcexcellon(edited_obj)
  1882. # self.exc_editor.update_options(edited_obj)
  1883. self.exc_editor.deactivate()
  1884. # restore GUI to the Selected TAB
  1885. # Remove anything else in the GUI
  1886. self.ui.tool_scroll_area.takeWidget()
  1887. # delete the old object (the source object) if it was an empty one
  1888. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1889. old_name = edited_obj.options['name']
  1890. self.collection.delete_by_name(name=old_name)
  1891. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1892. else:
  1893. self.inform.emit('[WARNING_NOTCL] %s' %
  1894. _("Select a Gerber, Geometry or Excellon Object to update."))
  1895. return
  1896. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1897. elif response == bt_no:
  1898. # clean the Tools Tab
  1899. self.ui.tool_scroll_area.takeWidget()
  1900. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1901. self.ui.notebook.setTabText(2, "Tool")
  1902. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1903. if isinstance(edited_obj, GeometryObject):
  1904. self.geo_editor.deactivate()
  1905. edited_obj.build_ui()
  1906. elif isinstance(edited_obj, GerberObject):
  1907. self.grb_editor.deactivate_grb_editor()
  1908. edited_obj.build_ui()
  1909. elif isinstance(edited_obj, ExcellonObject):
  1910. self.exc_editor.deactivate()
  1911. edited_obj.build_ui()
  1912. else:
  1913. self.inform.emit('[WARNING_NOTCL] %s' %
  1914. _("Select a Gerber, Geometry or Excellon Object to update."))
  1915. return
  1916. elif response == bt_cancel:
  1917. return
  1918. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1919. # edited_obj.build_ui()
  1920. # Switch notebook to Selected page
  1921. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1922. else:
  1923. if isinstance(edited_obj, GeometryObject):
  1924. self.geo_editor.deactivate()
  1925. elif isinstance(edited_obj, GerberObject):
  1926. self.grb_editor.deactivate_grb_editor()
  1927. elif isinstance(edited_obj, ExcellonObject):
  1928. self.exc_editor.deactivate()
  1929. else:
  1930. self.inform.emit('[WARNING_NOTCL] %s' %
  1931. _("Select a Gerber, Geometry or Excellon Object to update."))
  1932. return
  1933. # if notebook is hidden we show it
  1934. if self.ui.splitter.sizes()[0] == 0:
  1935. self.ui.splitter.setSizes([1, 1])
  1936. # restore the call_source to app
  1937. self.call_source = 'app'
  1938. edited_obj.plot()
  1939. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1940. self.ui.plot_tab_area.protectTab(0)
  1941. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1942. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1943. self.ui.project_frame.setDisabled(False)
  1944. def get_last_folder(self):
  1945. """
  1946. Get the folder path from where the last file was opened.
  1947. :return: String, last opened folder path
  1948. """
  1949. return self.defaults["global_last_folder"]
  1950. def get_last_save_folder(self):
  1951. """
  1952. Get the folder path from where the last file was saved.
  1953. :return: String, last saved folder path
  1954. """
  1955. loc = self.defaults["global_last_save_folder"]
  1956. if loc is None:
  1957. loc = self.defaults["global_last_folder"]
  1958. if loc is None:
  1959. loc = os.path.dirname(__file__)
  1960. return loc
  1961. def info(self, msg):
  1962. """
  1963. Informs the user. Normally on the status bar, optionally
  1964. also on the shell.
  1965. :param msg: Text to write.
  1966. :return: None
  1967. """
  1968. # Type of message in brackets at the beginning of the message.
  1969. match = re.search(r"\[(.*)\](.*)", msg)
  1970. if match:
  1971. level = match.group(1)
  1972. msg_ = match.group(2)
  1973. self.ui.fcinfo.set_status(str(msg_), level=level)
  1974. if level.lower() == "error":
  1975. self.shell_message(msg, error=True, show=True)
  1976. elif level.lower() == "warning":
  1977. self.shell_message(msg, warning=True, show=True)
  1978. elif level.lower() == "error_notcl":
  1979. self.shell_message(msg, error=True, show=False)
  1980. elif level.lower() == "warning_notcl":
  1981. self.shell_message(msg, warning=True, show=False)
  1982. elif level.lower() == "success":
  1983. self.shell_message(msg, success=True, show=False)
  1984. elif level.lower() == "selected":
  1985. self.shell_message(msg, selected=True, show=False)
  1986. else:
  1987. self.shell_message(msg, show=False)
  1988. else:
  1989. self.ui.fcinfo.set_status(str(msg), level="info")
  1990. # make sure that if the message is to clear the infobar with a space
  1991. # is not printed over and over on the shell
  1992. if msg != '':
  1993. self.shell_message(msg)
  1994. def restore_toolbar_view(self):
  1995. """
  1996. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1997. was saved in the defaults dictionary.
  1998. :return: None
  1999. """
  2000. tb = self.defaults["global_toolbar_view"]
  2001. if tb & 1:
  2002. self.ui.toolbarfile.setVisible(True)
  2003. else:
  2004. self.ui.toolbarfile.setVisible(False)
  2005. if tb & 2:
  2006. self.ui.toolbargeo.setVisible(True)
  2007. else:
  2008. self.ui.toolbargeo.setVisible(False)
  2009. if tb & 4:
  2010. self.ui.toolbarview.setVisible(True)
  2011. else:
  2012. self.ui.toolbarview.setVisible(False)
  2013. if tb & 8:
  2014. self.ui.toolbartools.setVisible(True)
  2015. else:
  2016. self.ui.toolbartools.setVisible(False)
  2017. if tb & 16:
  2018. self.ui.exc_edit_toolbar.setVisible(True)
  2019. else:
  2020. self.ui.exc_edit_toolbar.setVisible(False)
  2021. if tb & 32:
  2022. self.ui.geo_edit_toolbar.setVisible(True)
  2023. else:
  2024. self.ui.geo_edit_toolbar.setVisible(False)
  2025. if tb & 64:
  2026. self.ui.grb_edit_toolbar.setVisible(True)
  2027. else:
  2028. self.ui.grb_edit_toolbar.setVisible(False)
  2029. if tb & 128:
  2030. self.ui.snap_toolbar.setVisible(True)
  2031. else:
  2032. self.ui.snap_toolbar.setVisible(False)
  2033. if tb & 256:
  2034. self.ui.toolbarshell.setVisible(True)
  2035. else:
  2036. self.ui.toolbarshell.setVisible(False)
  2037. def on_import_preferences(self):
  2038. """
  2039. Loads the application default settings from a saved file into
  2040. ``self.defaults`` dictionary.
  2041. :return: None
  2042. """
  2043. self.defaults.report_usage("on_import_preferences")
  2044. App.log.debug("App.on_import_preferences()")
  2045. # Show file chooser
  2046. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2047. try:
  2048. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2049. directory=self.data_path,
  2050. filter=filter_)
  2051. except TypeError:
  2052. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2053. filter=filter_)
  2054. filename = str(filename)
  2055. if filename == "":
  2056. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2057. return
  2058. # Load in the defaults from the chosen file
  2059. self.defaults.load(filename=filename)
  2060. self.preferencesUiManager.on_preferences_edited()
  2061. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2062. def on_export_preferences(self):
  2063. """
  2064. Save the defaults dictionary to a file.
  2065. :return: None
  2066. """
  2067. self.defaults.report_usage("on_export_preferences")
  2068. App.log.debug("on_export_preferences()")
  2069. # defaults_file_content = None
  2070. # Show file chooser
  2071. date = str(datetime.today()).rpartition('.')[0]
  2072. date = ''.join(c for c in date if c not in ':-')
  2073. date = date.replace(' ', '_')
  2074. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2075. try:
  2076. filename, _f = FCFileSaveDialog.get_saved_filename(
  2077. caption=_("Export FlatCAM Preferences"),
  2078. directory=self.data_path + '/preferences_' + date,
  2079. filter=filter__
  2080. )
  2081. except TypeError:
  2082. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2083. filename = str(filename)
  2084. if filename == "":
  2085. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2086. return
  2087. # Update options
  2088. self.preferencesUiManager.defaults_read_form()
  2089. self.defaults.propagate_defaults()
  2090. # Save update options
  2091. try:
  2092. self.defaults.write(filename=filename)
  2093. except Exception:
  2094. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2095. return
  2096. if self.defaults["global_open_style"] is False:
  2097. self.file_opened.emit("preferences", filename)
  2098. self.file_saved.emit("preferences", filename)
  2099. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2100. def save_to_file(self, content_to_save, txt_content):
  2101. """
  2102. Save something to a file.
  2103. :return: None
  2104. """
  2105. self.defaults.report_usage("save_to_file")
  2106. App.log.debug("save_to_file()")
  2107. self.date = str(datetime.today()).rpartition('.')[0]
  2108. self.date = ''.join(c for c in self.date if c not in ':-')
  2109. self.date = self.date.replace(' ', '_')
  2110. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2111. path_to_save = self.defaults["global_last_save_folder"] if \
  2112. self.defaults["global_last_save_folder"] is not None else self.data_path
  2113. try:
  2114. filename, _f = FCFileSaveDialog.get_saved_filename(
  2115. caption=_("Save to file"),
  2116. directory=path_to_save + '/file_' + self.date,
  2117. filter=filter__
  2118. )
  2119. except TypeError:
  2120. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2121. filename = str(filename)
  2122. if filename == "":
  2123. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2124. return
  2125. else:
  2126. try:
  2127. with open(filename, 'w') as f:
  2128. ___ = f.read()
  2129. except PermissionError:
  2130. self.inform.emit('[WARNING] %s' %
  2131. _("Permission denied, saving not possible.\n"
  2132. "Most likely another app is holding the file open and not accessible."))
  2133. return
  2134. except IOError:
  2135. App.log.debug('Creating a new file ...')
  2136. f = open(filename, 'w')
  2137. f.close()
  2138. except Exception:
  2139. e = sys.exc_info()[0]
  2140. App.log.error("Could not load the file.")
  2141. App.log.error(str(e))
  2142. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2143. return
  2144. # Save content
  2145. if filename.rpartition('.')[2].lower() == 'html':
  2146. file_content = content_to_save
  2147. else:
  2148. file_content = txt_content
  2149. try:
  2150. with open(filename, "w") as f:
  2151. f.write(file_content)
  2152. except Exception:
  2153. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2154. return
  2155. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2156. def save_geometry(self, x, y, width, height, notebook_width):
  2157. """
  2158. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2159. launch of the application.
  2160. :param x: X position of the main window
  2161. :param y: Y position of the main window
  2162. :param width: width of the main window
  2163. :param height: height of the main window
  2164. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2165. :return: None
  2166. """
  2167. self.defaults["global_def_win_x"] = x
  2168. self.defaults["global_def_win_y"] = y
  2169. self.defaults["global_def_win_w"] = width
  2170. self.defaults["global_def_win_h"] = height
  2171. self.defaults["global_def_notebook_width"] = notebook_width
  2172. self.preferencesUiManager.save_defaults()
  2173. def restore_main_win_geom(self):
  2174. try:
  2175. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2176. self.defaults["global_def_win_y"],
  2177. self.defaults["global_def_win_w"],
  2178. self.defaults["global_def_win_h"])
  2179. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2180. except KeyError as e:
  2181. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2182. def message_dialog(self, title, message, kind="info"):
  2183. """
  2184. Builds and show a custom QMessageBox to be used in FlatCAM.
  2185. :param title: title of the QMessageBox
  2186. :param message: message to be displayed
  2187. :param kind: type of QMessageBox; will display a specific icon.
  2188. :return:
  2189. """
  2190. icon = {"info": QtWidgets.QMessageBox.Information,
  2191. "warning": QtWidgets.QMessageBox.Warning,
  2192. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2193. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2194. dlg.setText(message)
  2195. dlg.exec_()
  2196. def register_recent(self, kind, filename):
  2197. """
  2198. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2199. dictionary.
  2200. :param kind: type of file that was opened
  2201. :param filename: the path and file name for the file that was opened
  2202. :return:
  2203. """
  2204. self.log.debug("register_recent()")
  2205. self.log.debug(" %s" % kind)
  2206. self.log.debug(" %s" % filename)
  2207. record = {'kind': str(kind), 'filename': str(filename)}
  2208. if record in self.recent:
  2209. return
  2210. if record in self.recent_projects:
  2211. return
  2212. if record['kind'] == 'project':
  2213. self.recent_projects.insert(0, record)
  2214. else:
  2215. self.recent.insert(0, record)
  2216. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2217. self.recent.pop()
  2218. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2219. self.recent_projects.pop()
  2220. try:
  2221. f = open(self.data_path + '/recent.json', 'w')
  2222. except IOError:
  2223. App.log.error("Failed to open recent items file for writing.")
  2224. self.inform.emit('[ERROR_NOTCL] %s' %
  2225. _('Failed to open recent files file for writing.'))
  2226. return
  2227. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2228. f.close()
  2229. try:
  2230. fp = open(self.data_path + '/recent_projects.json', 'w')
  2231. except IOError:
  2232. App.log.error("Failed to open recent items file for writing.")
  2233. self.inform.emit('[ERROR_NOTCL] %s' %
  2234. _('Failed to open recent projects file for writing.'))
  2235. return
  2236. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2237. fp.close()
  2238. # Re-build the recent items menu
  2239. self.setup_recent_items()
  2240. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2241. """
  2242. Creates a new specialized FlatCAMObj and attaches it to the application,
  2243. this is, updates the GUI accordingly, any other records and plots it.
  2244. This method is thread-safe.
  2245. Notes:
  2246. * If the name is in use, the self.collection will modify it
  2247. when appending it to the collection. There is no need to handle
  2248. name conflicts here.
  2249. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2250. :type kind: str
  2251. :param name: Name for the object.
  2252. :type name: str
  2253. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2254. The function is called with 2 parameters: the new object and the App instance.
  2255. :type initialize: function
  2256. :param plot: If to plot the resulting object
  2257. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2258. self.collection
  2259. :return: None
  2260. :rtype: None
  2261. """
  2262. App.log.debug("new_object()")
  2263. obj_plot = plot
  2264. obj_autoselected = autoselected
  2265. t0 = time.time() # Debug
  2266. # ## Create object
  2267. classdict = {
  2268. "gerber": GerberObject,
  2269. "excellon": ExcellonObject,
  2270. "cncjob": CNCJobObject,
  2271. "geometry": GeometryObject,
  2272. "script": ScriptObject,
  2273. "document": DocumentObject
  2274. }
  2275. App.log.debug("Calling object constructor...")
  2276. # Object creation/instantiation
  2277. obj = classdict[kind](name)
  2278. obj.units = self.options["units"]
  2279. # IMPORTANT
  2280. # The key names in defaults and options dictionary's are not random:
  2281. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2282. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2283. # copied to self.options. After that, below, depending on the type of
  2284. # object that is created, it will strip the name of the object and the underline (if the original key was
  2285. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2286. # "toolchange"
  2287. for option in self.options:
  2288. if option.find(kind + "_") == 0:
  2289. oname = option[len(kind) + 1:]
  2290. obj.options[oname] = self.options[option]
  2291. obj.isHovering = False
  2292. obj.notHovering = True
  2293. # Initialize as per user request
  2294. # User must take care to implement initialize
  2295. # in a thread-safe way as is is likely that we
  2296. # have been invoked in a separate thread.
  2297. t1 = time.time()
  2298. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2299. try:
  2300. return_value = initialize(obj, self)
  2301. except Exception as e:
  2302. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2303. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2304. msg += traceback.format_exc()
  2305. self.inform.emit(msg)
  2306. return "fail"
  2307. t2 = time.time()
  2308. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2309. if return_value == 'fail':
  2310. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2311. return "fail"
  2312. # Check units and convert if necessary
  2313. # This condition CAN be true because initialize() can change obj.units
  2314. if self.options["units"].upper() != obj.units.upper():
  2315. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2316. obj.convert_units(self.options["units"])
  2317. t3 = time.time()
  2318. self.log.debug("%f seconds converting units." % (t3 - t2))
  2319. # Create the bounding box for the object and then add the results to the obj.options
  2320. # But not for Scripts or for Documents
  2321. if kind != 'document' and kind != 'script':
  2322. try:
  2323. xmin, ymin, xmax, ymax = obj.bounds()
  2324. obj.options['xmin'] = xmin
  2325. obj.options['ymin'] = ymin
  2326. obj.options['xmax'] = xmax
  2327. obj.options['ymax'] = ymax
  2328. except Exception as e:
  2329. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2330. return "fail"
  2331. try:
  2332. if kind == 'excellon':
  2333. obj.fill_color = self.defaults["excellon_plot_fill"]
  2334. obj.outline_color = self.defaults["excellon_plot_line"]
  2335. if kind == 'gerber':
  2336. obj.fill_color = self.defaults["gerber_plot_fill"]
  2337. obj.outline_color = self.defaults["gerber_plot_line"]
  2338. except Exception as e:
  2339. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2340. # update the KeyWords list with the name of the file
  2341. self.myKeywords.append(obj.options['name'])
  2342. log.debug("Moving new object back to main thread.")
  2343. # Move the object to the main thread and let the app know that it is available.
  2344. obj.moveToThread(self.main_thread)
  2345. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2346. return obj
  2347. def new_excellon_object(self):
  2348. """
  2349. Creates a new, blank Excellon object.
  2350. :return: None
  2351. """
  2352. self.defaults.report_usage("new_excellon_object()")
  2353. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2354. def new_geometry_object(self):
  2355. """
  2356. Creates a new, blank and single-tool Geometry object.
  2357. :return: None
  2358. """
  2359. self.defaults.report_usage("new_geometry_object()")
  2360. def initialize(obj, app):
  2361. obj.multitool = False
  2362. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2363. def new_gerber_object(self):
  2364. """
  2365. Creates a new, blank Gerber object.
  2366. :return: None
  2367. """
  2368. self.defaults.report_usage("new_gerber_object()")
  2369. def initialize(grb_obj, app):
  2370. grb_obj.multitool = False
  2371. grb_obj.source_file = []
  2372. grb_obj.multigeo = False
  2373. grb_obj.follow = False
  2374. grb_obj.apertures = {}
  2375. grb_obj.solid_geometry = []
  2376. try:
  2377. grb_obj.options['xmin'] = 0
  2378. grb_obj.options['ymin'] = 0
  2379. grb_obj.options['xmax'] = 0
  2380. grb_obj.options['ymax'] = 0
  2381. except KeyError:
  2382. pass
  2383. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2384. def new_script_object(self):
  2385. """
  2386. Creates a new, blank TCL Script object.
  2387. :return: None
  2388. """
  2389. self.defaults.report_usage("new_script_object()")
  2390. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2391. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2392. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2393. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2394. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2395. # "ListSys, MillDrills,\n" \
  2396. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2397. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2398. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2399. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2400. # "# SubtractRectangle, Version, WriteGCode\n"
  2401. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2402. '# %s:\n' % _('TCL Tutorial is here') + \
  2403. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2404. '# %s:\n' % _("FlatCAM commands list")
  2405. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2406. "(displayed in Tcl Shell).")
  2407. def initialize(obj, app):
  2408. obj.source_file = deepcopy(new_source_file)
  2409. outname = 'new_script'
  2410. self.new_object('script', outname, initialize, plot=False)
  2411. def new_document_object(self):
  2412. """
  2413. Creates a new, blank Document object.
  2414. :return: None
  2415. """
  2416. self.defaults.report_usage("new_document_object()")
  2417. def initialize(obj, app):
  2418. obj.source_file = ""
  2419. self.new_object('document', 'new_document', initialize, plot=False)
  2420. def on_object_created(self, obj, plot, auto_select):
  2421. """
  2422. Event callback for object creation.
  2423. It will add the new object to the collection. After that it will plot the object in a threaded way
  2424. :param obj: The newly created FlatCAM object.
  2425. :param plot: if the newly create object t obe plotted
  2426. :param auto_select: if the newly created object to be autoselected after creation
  2427. :return: None
  2428. """
  2429. t0 = time.time() # DEBUG
  2430. self.log.debug("on_object_created()")
  2431. # The Collection might change the name if there is a collision
  2432. self.collection.append(obj)
  2433. # after adding the object to the collection always update the list of objects that are in the collection
  2434. self.all_objects_list = self.collection.get_list()
  2435. # self.inform.emit('[selected] %s created & selected: %s' %
  2436. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2437. if obj.kind == 'gerber':
  2438. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2439. kind=obj.kind.capitalize(),
  2440. color='green',
  2441. name=str(obj.options['name']), tx=_("created/selected"))
  2442. )
  2443. elif obj.kind == 'excellon':
  2444. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2445. kind=obj.kind.capitalize(),
  2446. color='brown',
  2447. name=str(obj.options['name']), tx=_("created/selected"))
  2448. )
  2449. elif obj.kind == 'cncjob':
  2450. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2451. kind=obj.kind.capitalize(),
  2452. color='blue',
  2453. name=str(obj.options['name']), tx=_("created/selected"))
  2454. )
  2455. elif obj.kind == 'geometry':
  2456. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2457. kind=obj.kind.capitalize(),
  2458. color='red',
  2459. name=str(obj.options['name']), tx=_("created/selected"))
  2460. )
  2461. elif obj.kind == 'script':
  2462. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2463. kind=obj.kind.capitalize(),
  2464. color='orange',
  2465. name=str(obj.options['name']), tx=_("created/selected"))
  2466. )
  2467. elif obj.kind == 'document':
  2468. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2469. kind=obj.kind.capitalize(),
  2470. color='darkCyan',
  2471. name=str(obj.options['name']), tx=_("created/selected"))
  2472. )
  2473. # update the SHELL auto-completer model with the name of the new object
  2474. self.shell._edit.set_model_data(self.myKeywords)
  2475. if auto_select:
  2476. # select the just opened object but deselect the previous ones
  2477. self.collection.set_all_inactive()
  2478. self.collection.set_active(obj.options["name"])
  2479. else:
  2480. self.collection.set_all_inactive()
  2481. # here it is done the object plotting
  2482. def worker_task(t_obj):
  2483. with self.proc_container.new(_("Plotting")):
  2484. if isinstance(t_obj, CNCJobObject):
  2485. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2486. else:
  2487. t_obj.plot()
  2488. t1 = time.time() # DEBUG
  2489. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2490. self.object_plotted.emit(t_obj)
  2491. # Send to worker
  2492. # self.worker.add_task(worker_task, [self])
  2493. if plot is True:
  2494. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2495. def on_object_changed(self, obj):
  2496. """
  2497. Called whenever the geometry of the object was changed in some way.
  2498. This require the update of it's bounding values so it can be the selected on canvas.
  2499. Update the bounding box data from obj.options
  2500. :param obj: the object that was changed
  2501. :return: None
  2502. """
  2503. xmin, ymin, xmax, ymax = obj.bounds()
  2504. obj.options['xmin'] = xmin
  2505. obj.options['ymin'] = ymin
  2506. obj.options['xmax'] = xmax
  2507. obj.options['ymax'] = ymax
  2508. log.debug("Object changed, updating the bounding box data on self.options")
  2509. # delete the old selection shape
  2510. self.delete_selection_shape()
  2511. self.should_we_save = True
  2512. def on_object_plotted(self):
  2513. """
  2514. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2515. :return: None
  2516. """
  2517. self.on_zoom_fit(None)
  2518. def on_about(self):
  2519. """
  2520. Displays the "about" dialog found in the Menu --> Help.
  2521. :return: None
  2522. """
  2523. self.defaults.report_usage("on_about")
  2524. version = self.version
  2525. version_date = self.version_date
  2526. beta = self.beta
  2527. class AboutDialog(QtWidgets.QDialog):
  2528. def __init__(self, app, parent=None):
  2529. QtWidgets.QDialog.__init__(self, parent)
  2530. self.app = app
  2531. # Icon and title
  2532. self.setWindowIcon(parent.app_icon)
  2533. self.setWindowTitle(_("About FlatCAM"))
  2534. self.resize(600, 200)
  2535. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2536. # self.setStyleSheet(
  2537. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2538. # "background-attachment: fixed"
  2539. # )
  2540. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2541. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2542. # palette = QtGui.QPalette()
  2543. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2544. # self.setPalette(palette)
  2545. logo = QtWidgets.QLabel()
  2546. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2547. title = QtWidgets.QLabel(
  2548. "<font size=8><B>FlatCAM</B></font><BR>"
  2549. "{title}<BR>"
  2550. "<BR>"
  2551. "<BR>"
  2552. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2553. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2554. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2555. "<B>{issue}</B></a><BR>".format(
  2556. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2557. devel=_("Development"),
  2558. down=_("DOWNLOAD"),
  2559. issue=_("Issue tracker"))
  2560. )
  2561. title.setOpenExternalLinks(True)
  2562. closebtn = QtWidgets.QPushButton(_("Close"))
  2563. tab_widget = QtWidgets.QTabWidget()
  2564. description_label = QtWidgets.QLabel(
  2565. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2566. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2567. version=version,
  2568. beta=('BETA' if beta else ''),
  2569. date=version_date,
  2570. arch=platform.architecture()[0])
  2571. )
  2572. description_label.setOpenExternalLinks(True)
  2573. lic_lbl_header = QtWidgets.QLabel(
  2574. '%s:<br>%s<br>' % (
  2575. _('Licensed under the MIT license'),
  2576. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2577. "http://www.opensource.org/licenses/mit-license.php</a>"
  2578. )
  2579. )
  2580. lic_lbl_header.setOpenExternalLinks(True)
  2581. lic_lbl_body = QtWidgets.QLabel(
  2582. _(
  2583. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2584. 'of this software and associated documentation files (the "Software"), to deal\n'
  2585. 'in the Software without restriction, including without limitation the rights\n'
  2586. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2587. 'copies of the Software, and to permit persons to whom the Software is\n'
  2588. 'furnished to do so, subject to the following conditions:\n\n'
  2589. 'The above copyright notice and this permission notice shall be included in\n'
  2590. 'all copies or substantial portions of the Software.\n\n'
  2591. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2592. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2593. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2594. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2595. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2596. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2597. 'THE SOFTWARE.'
  2598. )
  2599. )
  2600. attributions_label = QtWidgets.QLabel(
  2601. _(
  2602. 'Some of the icons used are from the following sources:<br>'
  2603. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2604. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2605. 'title="Flaticon">www.flaticon.com</a></div>'
  2606. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2607. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2608. )
  2609. )
  2610. attributions_label.setOpenExternalLinks(True)
  2611. # layouts
  2612. layout1 = QtWidgets.QVBoxLayout()
  2613. layout1_1 = QtWidgets.QHBoxLayout()
  2614. layout1_2 = QtWidgets.QHBoxLayout()
  2615. layout2 = QtWidgets.QHBoxLayout()
  2616. layout3 = QtWidgets.QHBoxLayout()
  2617. self.setLayout(layout1)
  2618. layout1.addLayout(layout1_1)
  2619. layout1.addLayout(layout1_2)
  2620. layout1.addLayout(layout2)
  2621. layout1.addLayout(layout3)
  2622. layout1_1.addStretch()
  2623. layout1_1.addWidget(description_label)
  2624. layout1_2.addWidget(tab_widget)
  2625. self.splash_tab = QtWidgets.QWidget()
  2626. self.splash_tab.setObjectName("splash_about")
  2627. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2628. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2629. tab_widget.addTab(self.splash_tab, _("Splash"))
  2630. self.programmmers_tab = QtWidgets.QWidget()
  2631. self.programmmers_tab.setObjectName("programmers_about")
  2632. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2633. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2634. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2635. self.translators_tab = QtWidgets.QWidget()
  2636. self.translators_tab.setObjectName("translators_about")
  2637. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2638. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2639. tab_widget.addTab(self.translators_tab, _("Translators"))
  2640. self.license_tab = QtWidgets.QWidget()
  2641. self.license_tab.setObjectName("license_about")
  2642. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2643. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2644. tab_widget.addTab(self.license_tab, _("License"))
  2645. self.attributions_tab = QtWidgets.QWidget()
  2646. self.attributions_tab.setObjectName("attributions_about")
  2647. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2648. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2649. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2650. self.splash_tab_layout.addWidget(logo, stretch=0)
  2651. self.splash_tab_layout.addWidget(title, stretch=1)
  2652. pal = QtGui.QPalette()
  2653. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2654. self.prog_grid_lay = QtWidgets.QGridLayout()
  2655. self.prog_grid_lay.setHorizontalSpacing(20)
  2656. self.prog_grid_lay.setColumnStretch(0, 0)
  2657. self.prog_grid_lay.setColumnStretch(2, 1)
  2658. prog_widget = QtWidgets.QWidget()
  2659. prog_widget.setLayout(self.prog_grid_lay)
  2660. prog_scroll = QtWidgets.QScrollArea()
  2661. prog_scroll.setWidget(prog_widget)
  2662. prog_scroll.setWidgetResizable(True)
  2663. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2664. prog_scroll.setPalette(pal)
  2665. self.programmmers_tab_layout.addWidget(prog_scroll)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2712. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2713. self.translator_grid_lay = QtWidgets.QGridLayout()
  2714. self.translator_grid_lay.setColumnStretch(0, 0)
  2715. self.translator_grid_lay.setColumnStretch(1, 0)
  2716. self.translator_grid_lay.setColumnStretch(2, 1)
  2717. self.translator_grid_lay.setColumnStretch(3, 0)
  2718. # trans_widget = QtWidgets.QWidget()
  2719. # trans_widget.setLayout(self.translator_grid_lay)
  2720. # self.translators_tab_layout.addWidget(trans_widget)
  2721. # self.translators_tab_layout.addStretch()
  2722. trans_widget = QtWidgets.QWidget()
  2723. trans_widget.setLayout(self.translator_grid_lay)
  2724. trans_scroll = QtWidgets.QScrollArea()
  2725. trans_scroll.setWidget(trans_widget)
  2726. trans_scroll.setWidgetResizable(True)
  2727. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2728. trans_scroll.setPalette(pal)
  2729. self.translators_tab_layout.addWidget(trans_scroll)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2758. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2759. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2760. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2761. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2762. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2763. self.translator_grid_lay.setColumnStretch(0, 0)
  2764. self.translators_tab_layout.addStretch()
  2765. self.license_tab_layout.addWidget(lic_lbl_header)
  2766. self.license_tab_layout.addWidget(lic_lbl_body)
  2767. self.license_tab_layout.addStretch()
  2768. self.attributions_tab_layout.addWidget(attributions_label)
  2769. self.attributions_tab_layout.addStretch()
  2770. layout3.addStretch()
  2771. layout3.addWidget(closebtn)
  2772. closebtn.clicked.connect(self.accept)
  2773. AboutDialog(app=self, parent=self.ui).exec_()
  2774. def install_bookmarks(self, book_dict=None):
  2775. """
  2776. Install the bookmarks actions in the Help menu -> Bookmarks
  2777. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2778. :return: None
  2779. """
  2780. if book_dict is None:
  2781. self.defaults["global_bookmarks"].update(
  2782. {
  2783. '1': ['FlatCAM', "http://flatcam.org"],
  2784. '2': ['Backup Site', ""]
  2785. }
  2786. )
  2787. else:
  2788. self.defaults["global_bookmarks"].clear()
  2789. self.defaults["global_bookmarks"].update(book_dict)
  2790. # first try to disconnect if somehow they get connected from elsewhere
  2791. for act in self.ui.menuhelp_bookmarks.actions():
  2792. try:
  2793. act.triggered.disconnect()
  2794. except TypeError:
  2795. pass
  2796. # clear all actions except the last one who is the Bookmark manager
  2797. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2798. pass
  2799. else:
  2800. self.ui.menuhelp_bookmarks.removeAction(act)
  2801. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2802. if self.defaults["global_bookmarks"]:
  2803. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2804. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2805. # the JSON is first making the keys as strings (therefore I have to use strings too
  2806. # or do the conversion :(
  2807. # )
  2808. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2809. # the '10' entry jsut after '1' therefore ordering as strings
  2810. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2811. key=lambda x: int(x[0]))
  2812. for entry, bookmark in sorted_bookmarks:
  2813. title = bookmark[0]
  2814. weblink = bookmark[1]
  2815. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2816. act.setText(title)
  2817. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2818. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2819. if title == 'Backup Site' and weblink == "":
  2820. act.triggered.connect(self.on_backup_site)
  2821. else:
  2822. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2823. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2824. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2825. def on_bookmarks_manager(self):
  2826. """
  2827. Adds the bookmark manager in a Tab in Plot Area
  2828. :return:
  2829. """
  2830. for idx in range(self.ui.plot_tab_area.count()):
  2831. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2832. # there can be only one instance of Bookmark Manager at one time
  2833. return
  2834. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2835. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2836. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2837. # add the tab if it was closed
  2838. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2839. # delete the absolute and relative position and messages in the infobar
  2840. self.ui.position_label.setText("")
  2841. # self.ui.rel_position_label.setText("")
  2842. # Switch plot_area to preferences page
  2843. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2844. def on_backup_site(self):
  2845. msgbox = QtWidgets.QMessageBox()
  2846. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2847. "1. FlatCAM.org website is down\n"
  2848. "2. Someone forked FlatCAM project and wants to point\n"
  2849. "to his own website\n\n"
  2850. "If you can't get any informations about FlatCAM beta\n"
  2851. "use the YouTube channel link from the Help menu."))
  2852. msgbox.setWindowTitle(_("Alternative website"))
  2853. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2854. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2855. msgbox.setDefaultButton(bt_yes)
  2856. msgbox.exec_()
  2857. # response = msgbox.clickedButton()
  2858. def on_file_savedefaults(self):
  2859. """
  2860. Callback for menu item File->Save Defaults. Saves application default options
  2861. ``self.defaults`` to current_defaults.FlatConfig.
  2862. :return: None
  2863. """
  2864. self.preferencesUiManager.save_defaults()
  2865. def final_save(self):
  2866. """
  2867. Callback for doing a preferences save to file whenever the application is about to quit.
  2868. If the project has changes, it will ask the user to save the project.
  2869. :return: None
  2870. """
  2871. if self.save_in_progress:
  2872. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2873. return
  2874. if self.should_we_save and self.collection.get_list():
  2875. msgbox = QtWidgets.QMessageBox()
  2876. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2877. "\n"
  2878. "Do you want to Save the project?"))
  2879. msgbox.setWindowTitle(_("Save changes"))
  2880. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2881. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2882. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2883. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2884. msgbox.setDefaultButton(bt_yes)
  2885. msgbox.exec_()
  2886. response = msgbox.clickedButton()
  2887. if response == bt_yes:
  2888. try:
  2889. self.trayIcon.hide()
  2890. except Exception:
  2891. pass
  2892. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2893. elif response == bt_no:
  2894. try:
  2895. self.trayIcon.hide()
  2896. except Exception:
  2897. pass
  2898. self.quit_application()
  2899. elif response == bt_cancel:
  2900. return
  2901. else:
  2902. try:
  2903. self.trayIcon.hide()
  2904. except Exception:
  2905. pass
  2906. self.quit_application()
  2907. def quit_application(self):
  2908. """
  2909. Called (as a pyslot or not) when the application is quit.
  2910. :return: None
  2911. """
  2912. self.preferencesUiManager.save_defaults(silent=True)
  2913. log.debug("App.quit_application() --> App Defaults saved.")
  2914. if self.cmd_line_headless != 1:
  2915. # save app state to file
  2916. stgs = QSettings("Open Source", "FlatCAM")
  2917. stgs.setValue('saved_gui_state', self.ui.saveState())
  2918. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2919. stgs.setValue(
  2920. 'language',
  2921. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2922. )
  2923. stgs.setValue(
  2924. 'notebook_font_size',
  2925. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2926. )
  2927. stgs.setValue(
  2928. 'axis_font_size',
  2929. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2930. )
  2931. stgs.setValue(
  2932. 'textbox_font_size',
  2933. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2934. )
  2935. stgs.setValue(
  2936. 'hud_font_size',
  2937. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2938. )
  2939. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2940. stgs.setValue(
  2941. 'machinist',
  2942. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2943. )
  2944. # This will write the setting to the platform specific storage.
  2945. del stgs
  2946. log.debug("App.quit_application() --> App UI state saved.")
  2947. # try to quit the Socket opened by ArgsThread class
  2948. try:
  2949. self.new_launch.stop.emit()
  2950. except Exception as err:
  2951. log.debug("App.quit_application() --> %s" % str(err))
  2952. # try to quit the QThread that run ArgsThread class
  2953. try:
  2954. self.th.quit()
  2955. except Exception as e:
  2956. log.debug("App.quit_application() --> %s" % str(e))
  2957. # terminate workers
  2958. self.workers.__del__()
  2959. # quit app by signalling for self.kill_app() method
  2960. # self.close_app_signal.emit()
  2961. QtWidgets.qApp.quit()
  2962. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2963. # we use the following command
  2964. minor_v = sys.version_info.minor
  2965. if minor_v < 8:
  2966. sys.exit(0)
  2967. else:
  2968. os._exit(0) # fix to work with Python 3.8
  2969. @staticmethod
  2970. def kill_app():
  2971. QtWidgets.qApp.quit()
  2972. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2973. # we use the following command
  2974. sys.exit(0)
  2975. def on_portable_checked(self, state):
  2976. """
  2977. Callback called when the checkbox in Preferences GUI is checked.
  2978. It will set the application as portable by creating the preferences and recent files in the
  2979. 'config' folder found in the FlatCAM installation folder.
  2980. :param state: boolean, the state of the checkbox when clicked/checked
  2981. :return:
  2982. """
  2983. line_no = 0
  2984. data = None
  2985. if sys.platform != 'win32':
  2986. # this won't work in Linux or MacOS
  2987. return
  2988. # test if the app was frozen and choose the path for the configuration file
  2989. if getattr(sys, "frozen", False) is True:
  2990. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2991. else:
  2992. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2993. config_file = current_data_path + '\\configuration.txt'
  2994. try:
  2995. with open(config_file, 'r') as f:
  2996. try:
  2997. data = f.readlines()
  2998. except Exception as e:
  2999. log.debug('App.__init__() -->%s' % str(e))
  3000. return
  3001. except FileNotFoundError:
  3002. pass
  3003. for line in data:
  3004. line = line.strip('\n')
  3005. param = str(line).rpartition('=')
  3006. if param[0] == 'portable':
  3007. break
  3008. line_no += 1
  3009. if state:
  3010. data[line_no] = 'portable=True\n'
  3011. # create the new defauults files
  3012. # create current_defaults.FlatConfig file if there is none
  3013. try:
  3014. f = open(current_data_path + '/current_defaults.FlatConfig')
  3015. f.close()
  3016. except IOError:
  3017. App.log.debug('Creating empty current_defaults.FlatConfig')
  3018. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3019. json.dump({}, f)
  3020. f.close()
  3021. # create factory_defaults.FlatConfig file if there is none
  3022. try:
  3023. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3024. f.close()
  3025. except IOError:
  3026. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3027. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3028. json.dump({}, f)
  3029. f.close()
  3030. try:
  3031. f = open(current_data_path + '/recent.json')
  3032. f.close()
  3033. except IOError:
  3034. App.log.debug('Creating empty recent.json')
  3035. f = open(current_data_path + '/recent.json', 'w')
  3036. json.dump([], f)
  3037. f.close()
  3038. try:
  3039. fp = open(current_data_path + '/recent_projects.json')
  3040. fp.close()
  3041. except IOError:
  3042. App.log.debug('Creating empty recent_projects.json')
  3043. fp = open(current_data_path + '/recent_projects.json', 'w')
  3044. json.dump([], fp)
  3045. fp.close()
  3046. # save the current defaults to the new defaults file
  3047. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3048. else:
  3049. data[line_no] = 'portable=False\n'
  3050. with open(config_file, 'w') as f:
  3051. f.writelines(data)
  3052. def on_register_files(self, obj_type=None):
  3053. """
  3054. Called whenever there is a need to register file extensions with FlatCAM.
  3055. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3056. :param obj_type: the type of object to be register for.
  3057. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3058. :return: None
  3059. """
  3060. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3061. new_reg_path = 'Software\\Classes\\'
  3062. # find if the current user is admin
  3063. try:
  3064. is_admin = os.getuid() == 0
  3065. except AttributeError:
  3066. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3067. if is_admin is True:
  3068. root_path = winreg.HKEY_LOCAL_MACHINE
  3069. else:
  3070. root_path = winreg.HKEY_CURRENT_USER
  3071. # create the keys
  3072. def set_reg(name, root_pth, new_reg_path, value):
  3073. try:
  3074. winreg.CreateKey(root_pth, new_reg_path)
  3075. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3076. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3077. return True
  3078. except WindowsError:
  3079. return False
  3080. # delete key in registry
  3081. def delete_reg(root_pth, reg_path, key_to_del):
  3082. key_to_del_path = reg_path + key_to_del
  3083. try:
  3084. winreg.DeleteKey(root_pth, key_to_del_path)
  3085. return True
  3086. except WindowsError:
  3087. return False
  3088. if obj_type is None or obj_type == 'excellon':
  3089. exc_list = \
  3090. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3091. exc_list = [x for x in exc_list if x != '']
  3092. # register all keys in the Preferences window
  3093. for ext in exc_list:
  3094. new_k = new_reg_path + '.%s' % ext
  3095. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3096. # and unregister those that are no longer in the Preferences windows but are in the file
  3097. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3098. if ext not in exc_list:
  3099. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3100. # now write the updated extensions to the self.defaults
  3101. # new_ext = ''
  3102. # for ext in exc_list:
  3103. # new_ext = new_ext + ext + ', '
  3104. # self.defaults["fa_excellon"] = new_ext
  3105. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3106. if obj_type is None or obj_type == 'gcode':
  3107. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3108. gco_list = [x for x in gco_list if x != '']
  3109. # register all keys in the Preferences window
  3110. for ext in gco_list:
  3111. new_k = new_reg_path + '.%s' % ext
  3112. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3113. # and unregister those that are no longer in the Preferences windows but are in the file
  3114. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3115. if ext not in gco_list:
  3116. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3117. # now write the updated extensions to the self.defaults
  3118. # new_ext = ''
  3119. # for ext in gco_list:
  3120. # new_ext = new_ext + ext + ', '
  3121. # self.defaults["fa_gcode"] = new_ext
  3122. self.inform.emit('[success] %s' %
  3123. _("Selected GCode file extensions registered with FlatCAM."))
  3124. if obj_type is None or obj_type == 'gerber':
  3125. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3126. grb_list = [x for x in grb_list if x != '']
  3127. # register all keys in the Preferences window
  3128. for ext in grb_list:
  3129. new_k = new_reg_path + '.%s' % ext
  3130. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3131. # and unregister those that are no longer in the Preferences windows but are in the file
  3132. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3133. if ext not in grb_list:
  3134. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3135. # now write the updated extensions to the self.defaults
  3136. # new_ext = ''
  3137. # for ext in grb_list:
  3138. # new_ext = new_ext + ext + ', '
  3139. # self.defaults["fa_gerber"] = new_ext
  3140. self.inform.emit('[success] %s' %
  3141. _("Selected Gerber file extensions registered with FlatCAM."))
  3142. def add_extension(self, ext_type):
  3143. """
  3144. Add a file extension to the list for a specific object
  3145. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3146. :return:
  3147. """
  3148. if ext_type == 'excellon':
  3149. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3150. if new_ext == '':
  3151. return
  3152. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3153. if new_ext in old_val:
  3154. return
  3155. old_val.append(new_ext)
  3156. old_val.sort()
  3157. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3158. if ext_type == 'gcode':
  3159. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3160. if new_ext == '':
  3161. return
  3162. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3163. if new_ext in old_val:
  3164. return
  3165. old_val.append(new_ext)
  3166. old_val.sort()
  3167. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3168. if ext_type == 'gerber':
  3169. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3170. if new_ext == '':
  3171. return
  3172. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3173. if new_ext in old_val:
  3174. return
  3175. old_val.append(new_ext)
  3176. old_val.sort()
  3177. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3178. if ext_type == 'keyword':
  3179. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3180. if new_kw == '':
  3181. return
  3182. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3183. if new_kw in old_val:
  3184. return
  3185. old_val.append(new_kw)
  3186. old_val.sort()
  3187. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3188. # update the self.myKeywords so the model is updated
  3189. self.autocomplete_kw_list = \
  3190. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3191. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3192. self.shell._edit.set_model_data(self.myKeywords)
  3193. def del_extension(self, ext_type):
  3194. """
  3195. Remove a file extension from the list for a specific object
  3196. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3197. :return:
  3198. """
  3199. if ext_type == 'excellon':
  3200. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3201. if new_ext == '':
  3202. return
  3203. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3204. if new_ext not in old_val:
  3205. return
  3206. old_val.remove(new_ext)
  3207. old_val.sort()
  3208. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3209. if ext_type == 'gcode':
  3210. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3211. if new_ext == '':
  3212. return
  3213. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3214. if new_ext not in old_val:
  3215. return
  3216. old_val.remove(new_ext)
  3217. old_val.sort()
  3218. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3219. if ext_type == 'gerber':
  3220. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3221. if new_ext == '':
  3222. return
  3223. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3224. if new_ext not in old_val:
  3225. return
  3226. old_val.remove(new_ext)
  3227. old_val.sort()
  3228. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3229. if ext_type == 'keyword':
  3230. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3231. if new_kw == '':
  3232. return
  3233. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3234. if new_kw not in old_val:
  3235. return
  3236. old_val.remove(new_kw)
  3237. old_val.sort()
  3238. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3239. # update the self.myKeywords so the model is updated
  3240. self.autocomplete_kw_list = \
  3241. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3242. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3243. self.shell._edit.set_model_data(self.myKeywords)
  3244. def restore_extensions(self, ext_type):
  3245. """
  3246. Restore all file extensions associations with FlatCAM, for a specific object
  3247. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3248. :return:
  3249. """
  3250. if ext_type == 'excellon':
  3251. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3252. # for the ability to open Excellon files with .txt extension
  3253. new_exc_list = deepcopy(self.exc_list)
  3254. try:
  3255. new_exc_list.remove('txt')
  3256. except ValueError:
  3257. pass
  3258. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3259. if ext_type == 'gcode':
  3260. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3261. if ext_type == 'gerber':
  3262. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3263. if ext_type == 'keyword':
  3264. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3265. # update the self.myKeywords so the model is updated
  3266. self.autocomplete_kw_list = self.default_keywords
  3267. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3268. self.shell._edit.set_model_data(self.myKeywords)
  3269. def delete_all_extensions(self, ext_type):
  3270. """
  3271. Delete all file extensions associations with FlatCAM, for a specific object
  3272. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3273. :return:
  3274. """
  3275. if ext_type == 'excellon':
  3276. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3277. if ext_type == 'gcode':
  3278. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3279. if ext_type == 'gerber':
  3280. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3281. if ext_type == 'keyword':
  3282. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3283. # update the self.myKeywords so the model is updated
  3284. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3285. self.shell._edit.set_model_data(self.myKeywords)
  3286. def on_edit_join(self, name=None):
  3287. """
  3288. Callback for Edit->Join. Joins the selected geometry objects into
  3289. a new one.
  3290. :return: None
  3291. """
  3292. self.defaults.report_usage("on_edit_join()")
  3293. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3294. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3295. geo_type_set = set()
  3296. objs = self.collection.get_selected()
  3297. if len(objs) < 2:
  3298. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3299. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3300. return 'fail'
  3301. for obj in objs:
  3302. geo_type_set.add(obj.multigeo)
  3303. # if len(geo_type_list) == 1 means that all list elements are the same
  3304. if len(geo_type_set) != 1:
  3305. self.inform.emit('[ERROR] %s' %
  3306. _("Failed join. The Geometry objects are of different types.\n"
  3307. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3308. "convert from one to another and retry joining \n"
  3309. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3310. "the result may not be what was expected. \n"
  3311. "Check the generated GCODE."))
  3312. return
  3313. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3314. if True in geo_type_set:
  3315. def initialize(geo_obj, app):
  3316. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3317. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3318. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3319. for v in geo_obj.tools.values():
  3320. v['data']['name'] = obj_name_multi
  3321. self.new_object("geometry", obj_name_multi, initialize)
  3322. else:
  3323. def initialize(geo_obj, app):
  3324. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3325. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3326. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3327. for v in geo_obj.tools.values():
  3328. v['data']['name'] = obj_name_single
  3329. self.new_object("geometry", obj_name_single, initialize)
  3330. self.should_we_save = True
  3331. def on_edit_join_exc(self):
  3332. """
  3333. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3334. a new Excellon.
  3335. :return: None
  3336. """
  3337. self.defaults.report_usage("on_edit_join_exc()")
  3338. objs = self.collection.get_selected()
  3339. for obj in objs:
  3340. if not isinstance(obj, ExcellonObject):
  3341. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3342. return
  3343. if len(objs) < 2:
  3344. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3345. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3346. return 'fail'
  3347. def initialize(exc_obj, app):
  3348. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3349. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3350. self.new_object("excellon", 'Combo_Excellon', initialize)
  3351. self.should_we_save = True
  3352. def on_edit_join_grb(self):
  3353. """
  3354. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3355. a new Gerber object.
  3356. :return: None
  3357. """
  3358. self.defaults.report_usage("on_edit_join_grb()")
  3359. objs = self.collection.get_selected()
  3360. for obj in objs:
  3361. if not isinstance(obj, GerberObject):
  3362. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3363. return
  3364. if len(objs) < 2:
  3365. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3366. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3367. return 'fail'
  3368. def initialize(grb_obj, app):
  3369. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3370. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3371. self.new_object("gerber", 'Combo_Gerber', initialize)
  3372. self.should_we_save = True
  3373. def on_convert_singlegeo_to_multigeo(self):
  3374. """
  3375. Called for converting a Geometry object from single-geo to multi-geo.
  3376. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3377. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3378. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3379. the solid-geometry of that tool.
  3380. :return: None
  3381. """
  3382. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3383. obj = self.collection.get_active()
  3384. if obj is None:
  3385. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3386. return
  3387. if not isinstance(obj, GeometryObject):
  3388. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3389. return
  3390. obj.multigeo = True
  3391. for tooluid, dict_value in obj.tools.items():
  3392. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3393. if not isinstance(obj.solid_geometry, list):
  3394. obj.solid_geometry = [obj.solid_geometry]
  3395. # obj.solid_geometry[:] = []
  3396. obj.plot()
  3397. self.should_we_save = True
  3398. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3399. def on_convert_multigeo_to_singlegeo(self):
  3400. """
  3401. Called for converting a Geometry object from multi-geo to single-geo.
  3402. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3403. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3404. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3405. the solid-geometry of that tool.
  3406. :return: None
  3407. """
  3408. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3409. obj = self.collection.get_active()
  3410. if obj is None:
  3411. self.inform.emit('[ERROR_NOTCL] %s' %
  3412. _("Failed. Select a Geometry Object and try again."))
  3413. return
  3414. if not isinstance(obj, GeometryObject):
  3415. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3416. (_("Expected a GeometryObject, got"), type(obj)))
  3417. return
  3418. obj.multigeo = False
  3419. total_solid_geometry = []
  3420. for tooluid, dict_value in obj.tools.items():
  3421. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3422. # clear the original geometry
  3423. dict_value['solid_geometry'][:] = []
  3424. obj.solid_geometry = deepcopy(total_solid_geometry)
  3425. obj.plot()
  3426. self.should_we_save = True
  3427. self.inform.emit('[success] %s' %
  3428. _("A Geometry object was converted to SingleGeo type."))
  3429. def on_defaults_dict_change(self, field):
  3430. """
  3431. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3432. Edit -> Preferences tab window.
  3433. :param field: the key of the self.defaults dictionary that was changed.
  3434. :return: None
  3435. """
  3436. self.preferencesUiManager.defaults_write_form_field(field=field)
  3437. if field == "units":
  3438. self.set_screen_units(self.defaults['units'])
  3439. def set_screen_units(self, units):
  3440. """
  3441. Set the FlatCAM units on the status bar.
  3442. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3443. :return: None
  3444. """
  3445. self.ui.units_label.setText("[" + units.lower() + "]")
  3446. def on_toggle_units_click(self):
  3447. try:
  3448. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3449. except (TypeError, AttributeError):
  3450. pass
  3451. if self.defaults["units"] == 'MM':
  3452. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3453. else:
  3454. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3455. self.on_toggle_units(no_pref=True)
  3456. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3457. lambda: self.on_toggle_units(no_pref=False))
  3458. def on_toggle_units(self, no_pref=False):
  3459. """
  3460. Callback for the Units radio-button change in the Preferences tab.
  3461. Changes the application's default units adn for the project too.
  3462. If changing the project's units, the change propagates to all of
  3463. the objects in the project.
  3464. :return: None
  3465. """
  3466. self.defaults.report_usage("on_toggle_units")
  3467. if self.toggle_units_ignore:
  3468. return
  3469. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3470. # If option is the same, then ignore
  3471. if new_units == self.defaults["units"].upper():
  3472. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3473. return
  3474. # Keys in self.defaults for which to scale their values
  3475. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3476. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3477. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3478. "gerber_editor_ma_high",
  3479. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3480. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3481. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3482. "excellon_feedrate_probe", "excellon_milling_dia",
  3483. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3484. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3485. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3486. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3487. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3488. "geometry_extracut_length", "geometry_z_pdepth",
  3489. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3490. 'cncjob_tooldia',
  3491. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3492. "tools_paintnewdia",
  3493. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3494. "tools_nccnewdia", "tools_ncc_offset_value",
  3495. "tools_2sided_drilldia",
  3496. "tools_film_boundary", "tools_film_scale_stroke",
  3497. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3498. "tools_cutout_depthperpass",
  3499. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3500. "tools_panelize_spacing_rows",
  3501. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3502. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3503. "tools_transform_buffer_dis",
  3504. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3505. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3506. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3507. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3508. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3509. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3510. "tools_cr_h2h_val", "tools_cr_dh_val",
  3511. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3512. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3513. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3514. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3515. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3516. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3517. "tools_copper_thieving_mask_clearance",
  3518. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3519. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3520. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3521. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3522. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3523. "tools_invert_margin",
  3524. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3525. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3526. def scale_defaults(sfactor):
  3527. for dim in dimensions:
  3528. if dim in [
  3529. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3530. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3531. 'tools_transform_mirror_point'
  3532. ]:
  3533. if self.defaults[dim] is None or self.defaults[dim] == '':
  3534. continue
  3535. try:
  3536. coordinates = self.defaults[dim].split(",")
  3537. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3538. coords_xy[0] *= sfactor
  3539. coords_xy[1] *= sfactor
  3540. self.defaults[dim] = "%.*f, %.*f" % (
  3541. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3542. except Exception as e:
  3543. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3544. elif dim in [
  3545. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3546. ]:
  3547. if self.defaults[dim] is None or self.defaults[dim] == '':
  3548. continue
  3549. try:
  3550. self.defaults[dim] = float(self.defaults[dim])
  3551. tools_diameters = [self.defaults[dim]]
  3552. except ValueError:
  3553. try:
  3554. tools_string = self.defaults[dim].split(",")
  3555. tools_diameters = [eval(a) for a in tools_string if a != '']
  3556. except Exception as e:
  3557. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3558. continue
  3559. self.defaults[dim] = ''
  3560. td_len = len(tools_diameters)
  3561. if td_len > 1:
  3562. for t in range(td_len):
  3563. tools_diameters[t] *= sfactor
  3564. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3565. else:
  3566. tools_diameters[0] *= sfactor
  3567. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3568. elif dim in ['global_gridx', 'global_gridy']:
  3569. # format the number of decimals to the one specified in self.decimals
  3570. try:
  3571. val = float(self.defaults[dim]) * sfactor
  3572. except Exception as e:
  3573. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3574. continue
  3575. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3576. else:
  3577. # the number of decimals for the rest is kept unchanged
  3578. if self.defaults[dim]:
  3579. try:
  3580. val = float(self.defaults[dim]) * sfactor
  3581. except Exception as e:
  3582. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3583. continue
  3584. self.defaults[dim] = val
  3585. # The scaling factor depending on choice of units.
  3586. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3587. # Changing project units. Warn user.
  3588. msgbox = QtWidgets.QMessageBox()
  3589. msgbox.setWindowTitle(_("Toggle Units"))
  3590. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3591. msgbox.setText(_("Changing the units of the project\n"
  3592. "will scale all objects.\n\n"
  3593. "Do you want to continue?"))
  3594. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3595. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3596. msgbox.setDefaultButton(bt_ok)
  3597. msgbox.exec_()
  3598. response = msgbox.clickedButton()
  3599. if response == bt_ok:
  3600. if no_pref is False:
  3601. self.preferencesUiManager.defaults_read_form()
  3602. scale_defaults(factor)
  3603. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3604. self.defaults["units"] = new_units
  3605. # update the defaults from form, some may assume that the conversion is enough and it's not
  3606. self.on_options_app2project()
  3607. # update the objects
  3608. for obj in self.collection.get_list():
  3609. obj.convert_units(new_units)
  3610. # make that the properties stored in the object are also updated
  3611. self.object_changed.emit(obj)
  3612. # rebuild the object UI
  3613. obj.build_ui()
  3614. # change this only if the workspace is active
  3615. if self.defaults['global_workspace'] is True:
  3616. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3617. # adjust the grid values on the main toolbar
  3618. val_x = float(self.defaults['global_gridx']) * factor
  3619. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3620. current = self.collection.get_active()
  3621. if current is not None:
  3622. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3623. if not isinstance(current, GeometryObject):
  3624. current.to_form()
  3625. # replot all objects
  3626. self.plot_all()
  3627. # set the status labels to reflect the current FlatCAM units
  3628. self.set_screen_units(new_units)
  3629. # signal to the app that we changed the object properties and it should save the project
  3630. self.should_we_save = True
  3631. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3632. else:
  3633. # Undo toggling
  3634. self.toggle_units_ignore = True
  3635. if self.defaults['units'].upper() == 'MM':
  3636. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3637. else:
  3638. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3639. self.toggle_units_ignore = False
  3640. # store the grid values so they are not changed in the next step
  3641. val_x = float(self.defaults['global_gridx'])
  3642. val_y = float(self.defaults['global_gridy'])
  3643. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3644. self.preferencesUiManager.defaults_read_form()
  3645. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3646. # in self.defaults from the GUI elements but
  3647. # I don't want it for the grid values, so I update them here
  3648. self.defaults['global_gridx'] = val_x
  3649. self.defaults['global_gridy'] = val_y
  3650. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3651. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3652. def on_fullscreen(self, disable=False):
  3653. self.defaults.report_usage("on_fullscreen()")
  3654. flags = self.ui.windowFlags()
  3655. if self.toggle_fscreen is False and disable is False:
  3656. # self.ui.showFullScreen()
  3657. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3658. a = self.ui.geometry()
  3659. self.x_pos = a.x()
  3660. self.y_pos = a.y()
  3661. self.width = a.width()
  3662. self.height = a.height()
  3663. # set new geometry to full desktop rect
  3664. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3665. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3666. # everything else will not work without this hack. This happen in Windows.
  3667. # https://bugreports.qt.io/browse/QTBUG-41309
  3668. desktop = QtWidgets.QApplication.desktop()
  3669. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3670. rec = desktop.screenGeometry(screen)
  3671. x = rec.x() - 1
  3672. y = rec.y() - 1
  3673. h = rec.height() + 2
  3674. w = rec.width() + 2
  3675. self.ui.setGeometry(x, y, w, h)
  3676. self.ui.show()
  3677. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3678. tb.setVisible(False)
  3679. self.ui.snap_toolbar.setVisible(True) # This is always visible
  3680. # self.ui.splitter_left.setVisible(False)
  3681. self.ui.splitter.setSizes([0, 1])
  3682. self.toggle_fscreen = True
  3683. elif self.toggle_fscreen is True or disable is True:
  3684. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3685. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3686. self.ui.showNormal()
  3687. self.restore_toolbar_view()
  3688. # self.ui.splitter_left.setVisible(True)
  3689. self.toggle_fscreen = False
  3690. def on_toggle_plotarea(self):
  3691. self.defaults.report_usage("on_toggle_plotarea()")
  3692. try:
  3693. name = self.ui.plot_tab_area.widget(0).objectName()
  3694. except AttributeError:
  3695. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3696. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3697. self.ui.plot_tab_area.protectTab(0)
  3698. return
  3699. if name != 'plotarea_tab':
  3700. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3701. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3702. self.ui.plot_tab_area.protectTab(0)
  3703. else:
  3704. self.ui.plot_tab_area.closeTab(0)
  3705. def on_toggle_notebook(self):
  3706. if self.ui.splitter.sizes()[0] == 0:
  3707. self.ui.splitter.setSizes([1, 1])
  3708. self.ui.menu_toggle_nb.setChecked(True)
  3709. else:
  3710. self.ui.splitter.setSizes([0, 1])
  3711. self.ui.menu_toggle_nb.setChecked(False)
  3712. def on_toggle_axis(self):
  3713. self.defaults.report_usage("on_toggle_axis()")
  3714. if self.toggle_axis is False:
  3715. if self.is_legacy is False:
  3716. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3717. parent=self.plotcanvas.view.scene)
  3718. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3719. parent=self.plotcanvas.view.scene)
  3720. else:
  3721. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3722. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3723. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3724. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3725. self.plotcanvas.canvas.draw()
  3726. self.toggle_axis = True
  3727. else:
  3728. if self.is_legacy is False:
  3729. self.plotcanvas.v_line.parent = None
  3730. self.plotcanvas.h_line.parent = None
  3731. else:
  3732. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3733. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3734. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3735. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3736. self.plotcanvas.canvas.draw()
  3737. self.toggle_axis = False
  3738. def on_toggle_grid(self):
  3739. self.defaults.report_usage("on_toggle_grid()")
  3740. self.ui.grid_snap_btn.trigger()
  3741. def on_toggle_grid_lines(self):
  3742. self.defaults.report_usage("on_toggle_grd_lines()")
  3743. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3744. if tt_settings.contains("theme"):
  3745. theme = tt_settings.value('theme', type=str)
  3746. else:
  3747. theme = 'white'
  3748. if self.toggle_grid_lines is False:
  3749. if self.is_legacy is False:
  3750. if theme == 'white':
  3751. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3752. else:
  3753. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3754. else:
  3755. self.plotcanvas.axes.grid(True)
  3756. try:
  3757. self.plotcanvas.canvas.draw()
  3758. except IndexError:
  3759. pass
  3760. pass
  3761. self.toggle_grid_lines = True
  3762. else:
  3763. if self.is_legacy is False:
  3764. if theme == 'white':
  3765. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3766. else:
  3767. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3768. else:
  3769. self.plotcanvas.axes.grid(False)
  3770. try:
  3771. self.plotcanvas.canvas.draw()
  3772. except IndexError:
  3773. pass
  3774. self.toggle_grid_lines = False
  3775. if self.is_legacy is False:
  3776. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3777. # - perhaps is a bug in VisPy implementation
  3778. if self.grid_status():
  3779. self.app_cursor.enabled = False
  3780. self.app_cursor.enabled = True
  3781. else:
  3782. self.app_cursor.enabled = True
  3783. self.app_cursor.enabled = False
  3784. def on_update_exc_export(self, state):
  3785. """
  3786. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3787. if the update_excellon_cb checkbox is checked
  3788. :param state: state of the checkbox whose signals is tied to his slot
  3789. :return:
  3790. """
  3791. if state:
  3792. # first try to disconnect
  3793. try:
  3794. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3795. disconnect(self.on_excellon_format_changed)
  3796. except TypeError:
  3797. pass
  3798. try:
  3799. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3800. disconnect(self.on_excellon_format_changed)
  3801. except TypeError:
  3802. pass
  3803. try:
  3804. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3805. disconnect(self.on_excellon_format_changed)
  3806. except TypeError:
  3807. pass
  3808. try:
  3809. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3810. disconnect(self.on_excellon_format_changed)
  3811. except TypeError:
  3812. pass
  3813. try:
  3814. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3815. disconnect(self.on_excellon_zeros_changed)
  3816. except TypeError:
  3817. pass
  3818. try:
  3819. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3820. disconnect(self.on_excellon_zeros_changed)
  3821. except TypeError:
  3822. pass
  3823. # the connect them
  3824. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3825. self.on_excellon_format_changed)
  3826. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3827. self.on_excellon_format_changed)
  3828. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3829. self.on_excellon_format_changed)
  3830. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3831. self.on_excellon_format_changed)
  3832. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3833. self.on_excellon_zeros_changed)
  3834. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3835. self.on_excellon_units_changed)
  3836. else:
  3837. # disconnect the signals
  3838. try:
  3839. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3840. disconnect(self.on_excellon_format_changed)
  3841. except TypeError:
  3842. pass
  3843. try:
  3844. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3845. disconnect(self.on_excellon_format_changed)
  3846. except TypeError:
  3847. pass
  3848. try:
  3849. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3850. disconnect(self.on_excellon_format_changed)
  3851. except TypeError:
  3852. pass
  3853. try:
  3854. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3855. disconnect(self.on_excellon_format_changed)
  3856. except TypeError:
  3857. pass
  3858. try:
  3859. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3860. disconnect(self.on_excellon_zeros_changed)
  3861. except TypeError:
  3862. pass
  3863. try:
  3864. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3865. disconnect(self.on_excellon_zeros_changed)
  3866. except TypeError:
  3867. pass
  3868. def on_excellon_format_changed(self):
  3869. """
  3870. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3871. :return: None
  3872. """
  3873. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3874. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3875. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3876. )
  3877. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3878. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3879. )
  3880. else:
  3881. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3882. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3883. )
  3884. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3885. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3886. )
  3887. def on_excellon_zeros_changed(self):
  3888. """
  3889. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3890. :return: None
  3891. """
  3892. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3893. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3894. )
  3895. def on_excellon_units_changed(self):
  3896. """
  3897. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3898. :return: None
  3899. """
  3900. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3901. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3902. )
  3903. self.on_excellon_format_changed()
  3904. def on_film_color_entry(self):
  3905. self.defaults['tools_film_color'] = \
  3906. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3907. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3908. "background-color:%s;"
  3909. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3910. )
  3911. def on_film_color_button(self):
  3912. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3913. c_dialog = QtWidgets.QColorDialog()
  3914. film_color = c_dialog.getColor(initial=current_color)
  3915. if film_color.isValid() is False:
  3916. return
  3917. # if new color is different then mark that the Preferences are changed
  3918. if film_color != current_color:
  3919. self.preferencesUiManager.on_preferences_edited()
  3920. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3921. "background-color:%s;"
  3922. "border-color: dimgray" % str(film_color.name())
  3923. )
  3924. new_val_sel = str(film_color.name())
  3925. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3926. self.defaults['tools_film_color'] = new_val_sel
  3927. def on_qrcode_fill_color_entry(self):
  3928. self.defaults['tools_qrcode_fill_color'] = \
  3929. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3930. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3931. "background-color:%s;"
  3932. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3933. )
  3934. def on_qrcode_fill_color_button(self):
  3935. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3936. c_dialog = QtWidgets.QColorDialog()
  3937. fill_color = c_dialog.getColor(initial=current_color)
  3938. if fill_color.isValid() is False:
  3939. return
  3940. # if new color is different then mark that the Preferences are changed
  3941. if fill_color != current_color:
  3942. self.preferencesUiManager.on_preferences_edited()
  3943. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3944. "background-color:%s;"
  3945. "border-color: dimgray" % str(fill_color.name())
  3946. )
  3947. new_val_sel = str(fill_color.name())
  3948. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3949. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3950. def on_qrcode_back_color_entry(self):
  3951. self.defaults['tools_qrcode_back_color'] = \
  3952. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3953. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3954. "background-color:%s;"
  3955. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3956. )
  3957. def on_qrcode_back_color_button(self):
  3958. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3959. c_dialog = QtWidgets.QColorDialog()
  3960. back_color = c_dialog.getColor(initial=current_color)
  3961. if back_color.isValid() is False:
  3962. return
  3963. # if new color is different then mark that the Preferences are changed
  3964. if back_color != current_color:
  3965. self.preferencesUiManager.on_preferences_edited()
  3966. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3967. "background-color:%s;"
  3968. "border-color: dimgray" % str(back_color.name())
  3969. )
  3970. new_val_sel = str(back_color.name())
  3971. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3972. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3973. def on_tab_rmb_click(self, checked):
  3974. self.ui.notebook.set_detachable(val=checked)
  3975. self.defaults["global_tabs_detachable"] = checked
  3976. self.ui.plot_tab_area.set_detachable(val=checked)
  3977. self.defaults["global_tabs_detachable"] = checked
  3978. def on_tab_setup_context_menu(self):
  3979. initial_checked = self.defaults["global_tabs_detachable"]
  3980. action_name = str(_("Detachable Tabs"))
  3981. action = QtWidgets.QAction(self)
  3982. action.setCheckable(True)
  3983. action.setText(action_name)
  3984. action.setChecked(initial_checked)
  3985. self.ui.notebook.tabBar.addAction(action)
  3986. self.ui.plot_tab_area.tabBar.addAction(action)
  3987. try:
  3988. action.triggered.disconnect()
  3989. except TypeError:
  3990. pass
  3991. action.triggered.connect(self.on_tab_rmb_click)
  3992. def on_deselect_all(self):
  3993. self.collection.set_all_inactive()
  3994. self.delete_selection_shape()
  3995. def on_workspace_modified(self):
  3996. # self.save_defaults(silent=True)
  3997. if self.is_legacy is True:
  3998. self.plotcanvas.delete_workspace()
  3999. self.preferencesUiManager.defaults_read_form()
  4000. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4001. def on_workspace(self):
  4002. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4003. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4004. else:
  4005. self.plotcanvas.delete_workspace()
  4006. self.preferencesUiManager.defaults_read_form()
  4007. # self.save_defaults(silent=True)
  4008. def on_workspace_toggle(self):
  4009. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4010. try:
  4011. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4012. except TypeError:
  4013. pass
  4014. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4015. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4016. self.on_workspace()
  4017. def on_cursor_type(self, val):
  4018. """
  4019. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4020. :return: None
  4021. """
  4022. self.app_cursor.enabled = False
  4023. if val == 'small':
  4024. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4025. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4026. self.app_cursor = self.plotcanvas.new_cursor()
  4027. else:
  4028. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4029. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4030. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4031. if self.ui.grid_snap_btn.isChecked():
  4032. self.app_cursor.enabled = True
  4033. else:
  4034. self.app_cursor.enabled = False
  4035. def on_tool_add_keypress(self):
  4036. # ## Current application units in Upper Case
  4037. self.units = self.defaults['units'].upper()
  4038. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4039. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4040. if notebook_widget_name == 'selected_tab':
  4041. if self.collection.get_active().kind == 'geometry':
  4042. # Tool add works for Geometry only if Advanced is True in Preferences
  4043. if self.defaults["global_app_level"] == 'a':
  4044. tool_add_popup = FCInputDialog(title="New Tool ...",
  4045. text='Enter a Tool Diameter:',
  4046. min=0.0000, max=99.9999, decimals=4)
  4047. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4048. val, ok = tool_add_popup.get_value()
  4049. if ok:
  4050. if float(val) == 0:
  4051. self.inform.emit('[WARNING_NOTCL] %s' %
  4052. _("Please enter a tool diameter with non-zero value, in Float format."))
  4053. return
  4054. self.collection.get_active().on_tool_add(dia=float(val))
  4055. else:
  4056. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4057. else:
  4058. msgbox = QtWidgets.QMessageBox()
  4059. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4060. "Go to Preferences -> General - Show Advanced Options."))
  4061. msgbox.setWindowTitle("Tool adding ...")
  4062. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4063. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4064. msgbox.setDefaultButton(bt_ok)
  4065. msgbox.exec_()
  4066. # work only if the notebook tab on focus is the Tools_Tab
  4067. if notebook_widget_name == 'tool_tab':
  4068. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4069. # and only if the tool is NCC Tool
  4070. if tool_widget == self.ncclear_tool.toolName:
  4071. self.ncclear_tool.on_add_tool_by_key()
  4072. # and only if the tool is Paint Area Tool
  4073. elif tool_widget == self.paint_tool.toolName:
  4074. self.paint_tool.on_add_tool_by_key()
  4075. # and only if the tool is Solder Paste Dispensing Tool
  4076. elif tool_widget == self.paste_tool.toolName:
  4077. self.paste_tool.on_add_tool_by_key()
  4078. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4079. # See description below.
  4080. def on_delete_keypress(self):
  4081. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4082. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4083. if notebook_widget_name == 'selected_tab':
  4084. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4085. self.collection.get_active().on_tool_delete()
  4086. # work only if the notebook tab on focus is the Tools_Tab
  4087. elif notebook_widget_name == 'tool_tab':
  4088. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4089. # and only if the tool is NCC Tool
  4090. if tool_widget == self.ncclear_tool.toolName:
  4091. self.ncclear_tool.on_tool_delete()
  4092. # and only if the tool is Paint Tool
  4093. elif tool_widget == self.paint_tool.toolName:
  4094. self.paint_tool.on_tool_delete()
  4095. # and only if the tool is Solder Paste Dispensing Tool
  4096. elif tool_widget == self.paste_tool.toolName:
  4097. self.paste_tool.on_tool_delete()
  4098. else:
  4099. self.on_delete()
  4100. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4101. # some screens you have to be careful where you hover with your mouse.
  4102. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4103. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4104. # Complicated, I know :)
  4105. def on_delete(self, force_deletion=False):
  4106. """
  4107. Delete the currently selected FlatCAMObjs.
  4108. :param force_deletion: used by Tcl command
  4109. :return: None
  4110. """
  4111. self.defaults.report_usage("on_delete()")
  4112. response = None
  4113. bt_ok = None
  4114. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4115. # a geometry object before we update it.
  4116. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4117. and self.grb_editor.editor_active is False:
  4118. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4119. msgbox = QtWidgets.QMessageBox()
  4120. msgbox.setWindowTitle(_("Delete objects"))
  4121. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4122. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4123. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4124. "the selected objects?"))
  4125. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4126. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4127. msgbox.setDefaultButton(bt_ok)
  4128. msgbox.exec_()
  4129. response = msgbox.clickedButton()
  4130. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4131. response = bt_ok
  4132. if response == bt_ok:
  4133. if self.collection.get_active():
  4134. self.log.debug("App.on_delete()")
  4135. for obj_active in self.collection.get_selected():
  4136. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4137. if obj_active.kind == 'gerber':
  4138. for el in obj_active.mark_shapes:
  4139. obj_active.mark_shapes[el].clear(update=True)
  4140. obj_active.mark_shapes[el].enabled = False
  4141. # obj_active.mark_shapes[el] = None
  4142. del el
  4143. elif isinstance(obj_active, CNCJobObject):
  4144. try:
  4145. obj_active.text_col.enabled = False
  4146. del obj_active.text_col
  4147. obj_active.annotation.clear(update=True)
  4148. del obj_active.annotation
  4149. except AttributeError as e:
  4150. log.debug(
  4151. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4152. )
  4153. while self.collection.get_selected():
  4154. self.delete_first_selected()
  4155. self.inform.emit('%s...' % _("Object(s) deleted"))
  4156. # make sure that the selection shape is deleted, too
  4157. self.delete_selection_shape()
  4158. # if there are no longer objects delete also the exclusion areas shapes
  4159. if not self.collection.get_list():
  4160. self.exc_areas.clear_shapes()
  4161. else:
  4162. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4163. else:
  4164. self.inform.emit(_("Save the work in Editor and try again ..."))
  4165. def delete_first_selected(self):
  4166. # Keep this for later
  4167. try:
  4168. sel_obj = self.collection.get_active()
  4169. name = sel_obj.options["name"]
  4170. isPlotted = sel_obj.options["plot"]
  4171. except AttributeError:
  4172. self.log.debug("Nothing selected for deletion")
  4173. return
  4174. if self.is_legacy is True:
  4175. # Remove plot only if the object was plotted otherwise delaxes will fail
  4176. if isPlotted:
  4177. try:
  4178. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4179. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4180. except Exception as e:
  4181. log.debug("App.delete_first_selected() --> %s" % str(e))
  4182. self.plotcanvas.auto_adjust_axes()
  4183. # Remove from dictionary
  4184. self.collection.delete_active()
  4185. # Clear form
  4186. self.setup_component_editor()
  4187. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4188. def on_set_origin(self):
  4189. """
  4190. Set the origin to the left mouse click position
  4191. :return: None
  4192. """
  4193. # display the message for the user
  4194. # and ask him to click on the desired position
  4195. self.defaults.report_usage("on_set_origin()")
  4196. def origin_replot():
  4197. def worker_task():
  4198. with self.proc_container.new('%s...' % _("Plotting")):
  4199. for obj in self.collection.get_list():
  4200. obj.plot()
  4201. self.plotcanvas.fit_view()
  4202. if self.is_legacy:
  4203. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4204. else:
  4205. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4206. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4207. self.inform.emit(_('Click to set the origin ...'))
  4208. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4209. # first disconnect it as it may have been used by something else
  4210. try:
  4211. self.replot_signal.disconnect()
  4212. except TypeError:
  4213. pass
  4214. self.replot_signal[list].connect(origin_replot)
  4215. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4216. """
  4217. :param event:
  4218. :param location:
  4219. :param noplot:
  4220. :param use_thread:
  4221. :return:
  4222. """
  4223. noplot_sig = noplot
  4224. def worker_task():
  4225. with self.proc_container.new(_("Setting Origin...")):
  4226. obj_list = self.collection.get_list()
  4227. for obj in obj_list:
  4228. obj.offset((x, y))
  4229. self.object_changed.emit(obj)
  4230. # Update the object bounding box options
  4231. a, b, c, d = obj.bounds()
  4232. obj.options['xmin'] = a
  4233. obj.options['ymin'] = b
  4234. obj.options['xmax'] = c
  4235. obj.options['ymax'] = d
  4236. self.inform.emit('[success] %s...' % _('Origin set'))
  4237. for obj in obj_list:
  4238. out_name = obj.options["name"]
  4239. if obj.kind == 'gerber':
  4240. obj.source_file = self.export_gerber(
  4241. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4242. elif obj.kind == 'excellon':
  4243. obj.source_file = self.export_excellon(
  4244. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4245. if noplot_sig is False:
  4246. self.replot_signal.emit([])
  4247. if location is not None:
  4248. if len(location) != 2:
  4249. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4250. return 'fail'
  4251. x, y = location
  4252. if use_thread is True:
  4253. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4254. else:
  4255. worker_task()
  4256. self.should_we_save = True
  4257. return
  4258. if event.button == 1:
  4259. if self.is_legacy is False:
  4260. event_pos = event.pos
  4261. else:
  4262. event_pos = (event.xdata, event.ydata)
  4263. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4264. if self.grid_status():
  4265. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4266. else:
  4267. pos = pos_canvas
  4268. x = 0 - pos[0]
  4269. y = 0 - pos[1]
  4270. if use_thread is True:
  4271. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4272. else:
  4273. worker_task()
  4274. self.should_we_save = True
  4275. def on_move2origin(self, use_thread=True):
  4276. """
  4277. Move selected objects to origin.
  4278. :param use_thread: Control if to use threaded operation. Boolean.
  4279. :return:
  4280. """
  4281. def worker_task():
  4282. with self.proc_container.new(_("Moving to Origin...")):
  4283. obj_list = self.collection.get_selected()
  4284. if not obj_list:
  4285. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4286. return
  4287. xminlist = []
  4288. yminlist = []
  4289. # first get a bounding box to fit all
  4290. for obj in obj_list:
  4291. xmin, ymin, xmax, ymax = obj.bounds()
  4292. xminlist.append(xmin)
  4293. yminlist.append(ymin)
  4294. # get the minimum x,y for all objects selected
  4295. x = min(xminlist)
  4296. y = min(yminlist)
  4297. for obj in obj_list:
  4298. obj.offset((-x, -y))
  4299. self.object_changed.emit(obj)
  4300. # Update the object bounding box options
  4301. a, b, c, d = obj.bounds()
  4302. obj.options['xmin'] = a
  4303. obj.options['ymin'] = b
  4304. obj.options['xmax'] = c
  4305. obj.options['ymax'] = d
  4306. for obj in obj_list:
  4307. obj.plot()
  4308. for obj in obj_list:
  4309. out_name = obj.options["name"]
  4310. if obj.kind == 'gerber':
  4311. obj.source_file = self.export_gerber(
  4312. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4313. elif obj.kind == 'excellon':
  4314. obj.source_file = self.export_excellon(
  4315. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4316. self.inform.emit('[success] %s...' % _('Origin set'))
  4317. if use_thread is True:
  4318. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4319. else:
  4320. worker_task()
  4321. self.should_we_save = True
  4322. def on_jump_to(self, custom_location=None, fit_center=True):
  4323. """
  4324. Jump to a location by setting the mouse cursor location.
  4325. :param custom_location: Jump to a specified point. (x, y) tuple.
  4326. :param fit_center: If to fit view. Boolean.
  4327. :return:
  4328. """
  4329. self.defaults.report_usage("on_jump_to()")
  4330. if not custom_location:
  4331. dia_box_location = None
  4332. try:
  4333. dia_box_location = eval(self.clipboard.text())
  4334. except Exception:
  4335. pass
  4336. if type(dia_box_location) == tuple:
  4337. dia_box_location = str(dia_box_location)
  4338. else:
  4339. dia_box_location = None
  4340. # dia_box = Dialog_box(title=_("Jump to ..."),
  4341. # label=_("Enter the coordinates in format X,Y:"),
  4342. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4343. # initial_text=dia_box_location)
  4344. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4345. label=_("Enter the coordinates in format X,Y:"),
  4346. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4347. initial_text=dia_box_location,
  4348. reference=self.defaults['global_jump_ref'])
  4349. if dia_box.ok is True:
  4350. try:
  4351. location = eval(dia_box.location)
  4352. if not isinstance(location, tuple):
  4353. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4354. return
  4355. if dia_box.reference == 'rel':
  4356. rel_x = self.mouse[0] + location[0]
  4357. rel_y = self.mouse[1] + location[1]
  4358. location = (rel_x, rel_y)
  4359. self.defaults['global_jump_ref'] = dia_box.reference
  4360. except Exception:
  4361. return
  4362. else:
  4363. return
  4364. else:
  4365. location = custom_location
  4366. self.jump_signal.emit(location)
  4367. if fit_center:
  4368. self.plotcanvas.fit_center(loc=location)
  4369. cursor = QtGui.QCursor()
  4370. if self.is_legacy is False:
  4371. # I don't know where those differences come from but they are constant for the current
  4372. # execution of the application and they are multiples of a value around 0.0263mm.
  4373. # In a random way sometimes they are more sometimes they are less
  4374. # if units == 'MM':
  4375. # cal_factor = 0.0263
  4376. # else:
  4377. # cal_factor = 0.0263 / 25.4
  4378. cal_location = (location[0], location[1])
  4379. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4380. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4381. j_pos = (
  4382. int(canvas_origin.x() + round(jump_loc[0])),
  4383. int(canvas_origin.y() + round(jump_loc[1]))
  4384. )
  4385. cursor.setPos(j_pos[0], j_pos[1])
  4386. else:
  4387. # find the canvas origin which is in the top left corner
  4388. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4389. # determine the coordinates for the lowest left point of the canvas
  4390. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4391. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4392. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4393. # canvas) and the point (width, height) is in the top-right location
  4394. loc = self.plotcanvas.axes.transData.transform_point(location)
  4395. j_pos = (
  4396. int(x0 + loc[0]),
  4397. int(y0 - loc[1])
  4398. )
  4399. cursor.setPos(j_pos[0], j_pos[1])
  4400. self.plotcanvas.mouse = [location[0], location[1]]
  4401. if self.defaults["global_cursor_color_enabled"] is True:
  4402. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4403. else:
  4404. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4405. if self.grid_status():
  4406. # Update cursor
  4407. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4408. symbol='++', edge_color=self.cursor_color_3D,
  4409. edge_width=self.defaults["global_cursor_width"],
  4410. size=self.defaults["global_cursor_size"])
  4411. # Set the relative position label
  4412. dx = location[0] - float(self.rel_point1[0])
  4413. dy = location[1] - float(self.rel_point1[1])
  4414. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4415. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4416. # # Set the position label
  4417. #
  4418. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4419. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4420. units = self.defaults["units"].lower()
  4421. self.plotcanvas.text_hud.text = \
  4422. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4423. dx, units, dy, units, location[0], units, location[1], units)
  4424. self.inform.emit('[success] %s' % _("Done."))
  4425. return location
  4426. def on_locate(self, obj, fit_center=True):
  4427. """
  4428. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4429. :param obj: The object on which to locate certain points
  4430. :param fit_center: If to fit view. Boolean.
  4431. :return: A point location. (x, y) tuple.
  4432. """
  4433. self.defaults.report_usage("on_locate()")
  4434. if obj is None:
  4435. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4436. return 'fail'
  4437. class DialogBoxChoice(QtWidgets.QDialog):
  4438. def __init__(self, title=None, icon=None, choice='bl'):
  4439. """
  4440. :param title: string with the window title
  4441. """
  4442. super(DialogBoxChoice, self).__init__()
  4443. self.ok = False
  4444. self.setWindowIcon(icon)
  4445. self.setWindowTitle(str(title))
  4446. self.form = QtWidgets.QFormLayout(self)
  4447. self.ref_radio = RadioSet([
  4448. {"label": _("Bottom-Left"), "value": "bl"},
  4449. {"label": _("Top-Left"), "value": "tl"},
  4450. {"label": _("Bottom-Right"), "value": "br"},
  4451. {"label": _("Top-Right"), "value": "tr"},
  4452. {"label": _("Center"), "value": "c"}
  4453. ], orientation='vertical', stretch=False)
  4454. self.ref_radio.set_value(choice)
  4455. self.form.addRow(self.ref_radio)
  4456. self.button_box = QtWidgets.QDialogButtonBox(
  4457. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4458. Qt.Horizontal, parent=self)
  4459. self.form.addRow(self.button_box)
  4460. self.button_box.accepted.connect(self.accept)
  4461. self.button_box.rejected.connect(self.reject)
  4462. if self.exec_() == QtWidgets.QDialog.Accepted:
  4463. self.ok = True
  4464. self.location_point = self.ref_radio.get_value()
  4465. else:
  4466. self.ok = False
  4467. self.location_point = None
  4468. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4469. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4470. choice=self.defaults['global_locate_pt'])
  4471. if dia_box.ok is True:
  4472. try:
  4473. location_point = dia_box.location_point
  4474. self.defaults['global_locate_pt'] = dia_box.location_point
  4475. except Exception:
  4476. return
  4477. else:
  4478. return
  4479. loc_b = obj.bounds()
  4480. if location_point == 'bl':
  4481. location = (loc_b[0], loc_b[1])
  4482. elif location_point == 'tl':
  4483. location = (loc_b[0], loc_b[3])
  4484. elif location_point == 'br':
  4485. location = (loc_b[2], loc_b[1])
  4486. elif location_point == 'tr':
  4487. location = (loc_b[2], loc_b[3])
  4488. else:
  4489. # center
  4490. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4491. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4492. location = (cx, cy)
  4493. self.locate_signal.emit(location, location_point)
  4494. if fit_center:
  4495. self.plotcanvas.fit_center(loc=location)
  4496. cursor = QtGui.QCursor()
  4497. if self.is_legacy is False:
  4498. # I don't know where those differences come from but they are constant for the current
  4499. # execution of the application and they are multiples of a value around 0.0263mm.
  4500. # In a random way sometimes they are more sometimes they are less
  4501. # if units == 'MM':
  4502. # cal_factor = 0.0263
  4503. # else:
  4504. # cal_factor = 0.0263 / 25.4
  4505. cal_location = (location[0], location[1])
  4506. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4507. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4508. j_pos = (
  4509. int(canvas_origin.x() + round(jump_loc[0])),
  4510. int(canvas_origin.y() + round(jump_loc[1]))
  4511. )
  4512. cursor.setPos(j_pos[0], j_pos[1])
  4513. else:
  4514. # find the canvas origin which is in the top left corner
  4515. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4516. # determine the coordinates for the lowest left point of the canvas
  4517. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4518. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4519. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4520. # canvas) and the point (width, height) is in the top-right location
  4521. loc = self.plotcanvas.axes.transData.transform_point(location)
  4522. j_pos = (
  4523. int(x0 + loc[0]),
  4524. int(y0 - loc[1])
  4525. )
  4526. cursor.setPos(j_pos[0], j_pos[1])
  4527. self.plotcanvas.mouse = [location[0], location[1]]
  4528. if self.defaults["global_cursor_color_enabled"] is True:
  4529. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4530. else:
  4531. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4532. if self.grid_status():
  4533. # Update cursor
  4534. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4535. symbol='++', edge_color=self.cursor_color_3D,
  4536. edge_width=self.defaults["global_cursor_width"],
  4537. size=self.defaults["global_cursor_size"])
  4538. # Set the relative position label
  4539. self.dx = location[0] - float(self.rel_point1[0])
  4540. self.dy = location[1] - float(self.rel_point1[1])
  4541. # Set the position label
  4542. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4543. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4544. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4545. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4546. units = self.defaults["units"].lower()
  4547. self.plotcanvas.text_hud.text = \
  4548. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4549. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4550. self.inform.emit('[success] %s' % _("Done."))
  4551. return location
  4552. def on_copy_command(self):
  4553. """
  4554. Will copy a selection of objects, creating new objects.
  4555. :return:
  4556. """
  4557. self.defaults.report_usage("on_copy_command()")
  4558. def initialize(obj_init, app):
  4559. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4560. try:
  4561. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4562. except AttributeError:
  4563. pass
  4564. try:
  4565. obj_init.apertures = deepcopy(obj.apertures)
  4566. except AttributeError:
  4567. pass
  4568. try:
  4569. if obj.tools:
  4570. obj_init.tools = deepcopy(obj.tools)
  4571. except Exception as err:
  4572. log.debug("App.on_copy_command() --> %s" % str(err))
  4573. try:
  4574. obj_init.source_file = deepcopy(obj.source_file)
  4575. except (AttributeError, TypeError):
  4576. pass
  4577. def initialize_excellon(obj_init, app):
  4578. obj_init.source_file = deepcopy(obj.source_file)
  4579. obj_init.tools = deepcopy(obj.tools)
  4580. # drills are offset, so they need to be deep copied
  4581. obj_init.drills = deepcopy(obj.drills)
  4582. # slots are offset, so they need to be deep copied
  4583. obj_init.slots = deepcopy(obj.slots)
  4584. obj_init.create_geometry()
  4585. def initialize_script(obj_init, app_obj):
  4586. obj_init.source_file = deepcopy(obj.source_file)
  4587. def initialize_document(obj_init, app_obj):
  4588. obj_init.source_file = deepcopy(obj.source_file)
  4589. for obj in self.collection.get_selected():
  4590. obj_name = obj.options["name"]
  4591. try:
  4592. if isinstance(obj, ExcellonObject):
  4593. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4594. elif isinstance(obj, GerberObject):
  4595. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4596. elif isinstance(obj, GeometryObject):
  4597. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4598. elif isinstance(obj, ScriptObject):
  4599. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4600. elif isinstance(obj, DocumentObject):
  4601. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4602. except Exception as e:
  4603. return "Operation failed: %s" % str(e)
  4604. def on_copy_object2(self, custom_name):
  4605. def initialize_geometry(obj_init, app):
  4606. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4607. try:
  4608. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4609. except AttributeError:
  4610. pass
  4611. try:
  4612. obj_init.apertures = deepcopy(obj.apertures)
  4613. except AttributeError:
  4614. pass
  4615. try:
  4616. if obj.tools:
  4617. obj_init.tools = deepcopy(obj.tools)
  4618. except Exception as ee:
  4619. log.debug("on_copy_object2() --> %s" % str(ee))
  4620. def initialize_gerber(obj_init, app):
  4621. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4622. obj_init.apertures = deepcopy(obj.apertures)
  4623. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4624. def initialize_excellon(obj_init, app):
  4625. obj_init.tools = deepcopy(obj.tools)
  4626. # drills are offset, so they need to be deep copied
  4627. obj_init.drills = deepcopy(obj.drills)
  4628. # slots are offset, so they need to be deep copied
  4629. obj_init.slots = deepcopy(obj.slots)
  4630. obj_init.create_geometry()
  4631. for obj in self.collection.get_selected():
  4632. obj_name = obj.options["name"]
  4633. try:
  4634. if isinstance(obj, ExcellonObject):
  4635. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4636. elif isinstance(obj, GerberObject):
  4637. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4638. elif isinstance(obj, GeometryObject):
  4639. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4640. except Exception as er:
  4641. return "Operation failed: %s" % str(er)
  4642. def on_rename_object(self, text):
  4643. """
  4644. Will rename an object.
  4645. :param text: New name for the object.
  4646. :return:
  4647. """
  4648. self.defaults.report_usage("on_rename_object()")
  4649. named_obj = self.collection.get_active()
  4650. for obj in named_obj:
  4651. if obj is list:
  4652. self.on_rename_object(text)
  4653. else:
  4654. try:
  4655. obj.options['name'] = text
  4656. except Exception as e:
  4657. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4658. def convert_any2geo(self):
  4659. """
  4660. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4661. :return:
  4662. """
  4663. self.defaults.report_usage("convert_any2geo()")
  4664. def initialize(obj_init, app):
  4665. obj_init.solid_geometry = obj.solid_geometry
  4666. try:
  4667. obj_init.follow_geometry = obj.follow_geometry
  4668. except AttributeError:
  4669. pass
  4670. try:
  4671. obj_init.apertures = obj.apertures
  4672. except AttributeError:
  4673. pass
  4674. try:
  4675. if obj.tools:
  4676. obj_init.tools = obj.tools
  4677. except AttributeError:
  4678. pass
  4679. def initialize_excellon(obj_init, app):
  4680. # objs = self.collection.get_selected()
  4681. # GeometryObject.merge(objs, obj)
  4682. solid_geo = []
  4683. for tool in obj.tools:
  4684. for geo in obj.tools[tool]['solid_geometry']:
  4685. solid_geo.append(geo)
  4686. obj_init.solid_geometry = deepcopy(solid_geo)
  4687. if not self.collection.get_selected():
  4688. log.warning("App.convert_any2geo --> No object selected")
  4689. self.inform.emit('[WARNING_NOTCL] %s' %
  4690. _("No object is selected. Select an object and try again."))
  4691. return
  4692. for obj in self.collection.get_selected():
  4693. obj_name = obj.options["name"]
  4694. try:
  4695. if isinstance(obj, ExcellonObject):
  4696. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4697. else:
  4698. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4699. except Exception as e:
  4700. return "Operation failed: %s" % str(e)
  4701. def convert_any2gerber(self):
  4702. """
  4703. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4704. :return:
  4705. """
  4706. self.defaults.report_usage("convert_any2gerber()")
  4707. def initialize_geometry(obj_init, app):
  4708. apertures = {}
  4709. apid = 0
  4710. apertures[str(apid)] = {}
  4711. apertures[str(apid)]['geometry'] = []
  4712. for obj_orig in obj.solid_geometry:
  4713. new_elem = {}
  4714. new_elem['solid'] = obj_orig
  4715. try:
  4716. new_elem['follow'] = obj_orig.exterior
  4717. except AttributeError:
  4718. pass
  4719. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4720. apertures[str(apid)]['size'] = 0.0
  4721. apertures[str(apid)]['type'] = 'C'
  4722. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4723. obj_init.apertures = deepcopy(apertures)
  4724. def initialize_excellon(obj_init, app):
  4725. apertures = {}
  4726. apid = 10
  4727. for tool in obj.tools:
  4728. apertures[str(apid)] = {}
  4729. apertures[str(apid)]['geometry'] = []
  4730. for geo in obj.tools[tool]['solid_geometry']:
  4731. new_el = {}
  4732. new_el['solid'] = geo
  4733. new_el['follow'] = geo.exterior
  4734. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4735. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4736. apertures[str(apid)]['type'] = 'C'
  4737. apid += 1
  4738. # create solid_geometry
  4739. solid_geometry = []
  4740. for apid in apertures:
  4741. for geo_el in apertures[apid]['geometry']:
  4742. solid_geometry.append(geo_el['solid'])
  4743. solid_geometry = MultiPolygon(solid_geometry)
  4744. solid_geometry = solid_geometry.buffer(0.0000001)
  4745. obj_init.solid_geometry = deepcopy(solid_geometry)
  4746. obj_init.apertures = deepcopy(apertures)
  4747. # clear the working objects (perhaps not necessary due of Python GC)
  4748. apertures.clear()
  4749. if not self.collection.get_selected():
  4750. log.warning("App.convert_any2gerber --> No object selected")
  4751. self.inform.emit('[WARNING_NOTCL] %s' %
  4752. _("No object is selected. Select an object and try again."))
  4753. return
  4754. for obj in self.collection.get_selected():
  4755. obj_name = obj.options["name"]
  4756. try:
  4757. if isinstance(obj, ExcellonObject):
  4758. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4759. elif isinstance(obj, GeometryObject):
  4760. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4761. else:
  4762. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4763. except Exception as e:
  4764. return "Operation failed: %s" % str(e)
  4765. def abort_all_tasks(self):
  4766. """
  4767. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4768. on the first possible occasion.
  4769. :return:
  4770. """
  4771. if self.abort_flag is False:
  4772. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4773. self.abort_flag = True
  4774. self.cleanup.emit()
  4775. def app_is_idle(self):
  4776. if self.abort_flag:
  4777. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4778. self.abort_flag = False
  4779. def on_selectall(self):
  4780. """
  4781. Will draw a selection box shape around the selected objects.
  4782. :return:
  4783. """
  4784. self.defaults.report_usage("on_selectall()")
  4785. # delete the possible selection box around a possible selected object
  4786. self.delete_selection_shape()
  4787. for name in self.collection.get_names():
  4788. self.collection.set_active(name)
  4789. curr_sel_obj = self.collection.get_by_name(name)
  4790. # create the selection box around the selected object
  4791. if self.defaults['global_selection_shape'] is True:
  4792. self.draw_selection_shape(curr_sel_obj)
  4793. def on_preferences(self):
  4794. """
  4795. Adds the Preferences in a Tab in Plot Area
  4796. :return:
  4797. """
  4798. # add the tab if it was closed
  4799. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4800. # delete the absolute and relative position and messages in the infobar
  4801. self.ui.position_label.setText("")
  4802. # self.ui.rel_position_label.setText("")
  4803. # Switch plot_area to preferences page
  4804. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4805. # self.ui.show()
  4806. # detect changes in the preferences
  4807. for idx in range(self.ui.pref_tab_area.count()):
  4808. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4809. try:
  4810. try:
  4811. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4812. except (TypeError, AttributeError):
  4813. pass
  4814. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4815. except AttributeError:
  4816. pass
  4817. try:
  4818. try:
  4819. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4820. except (TypeError, AttributeError):
  4821. pass
  4822. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4823. except AttributeError:
  4824. pass
  4825. try:
  4826. try:
  4827. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4828. except (TypeError, AttributeError):
  4829. pass
  4830. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4831. except AttributeError:
  4832. pass
  4833. try:
  4834. try:
  4835. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4836. except (TypeError, AttributeError):
  4837. pass
  4838. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4839. except AttributeError:
  4840. pass
  4841. try:
  4842. try:
  4843. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4844. except (TypeError, AttributeError):
  4845. pass
  4846. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4847. except AttributeError:
  4848. pass
  4849. def on_tools_database(self, source='app'):
  4850. """
  4851. Adds the Tools Database in a Tab in Plot Area.
  4852. :return:
  4853. """
  4854. for idx in range(self.ui.plot_tab_area.count()):
  4855. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4856. # there can be only one instance of Tools Database at one time
  4857. return
  4858. if source == 'app':
  4859. self.tools_db_tab = ToolsDB2(
  4860. app=self,
  4861. parent=self.ui,
  4862. callback_on_edited=self.on_tools_db_edited,
  4863. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4864. )
  4865. elif source == 'ncc':
  4866. self.tools_db_tab = ToolsDB2(
  4867. app=self,
  4868. parent=self.ui,
  4869. callback_on_edited=self.on_tools_db_edited,
  4870. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4871. )
  4872. elif source == 'paint':
  4873. self.tools_db_tab = ToolsDB2(
  4874. app=self,
  4875. parent=self.ui,
  4876. callback_on_edited=self.on_tools_db_edited,
  4877. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4878. )
  4879. # add the tab if it was closed
  4880. try:
  4881. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4882. self.tools_db_tab.setObjectName("database_tab")
  4883. except Exception as e:
  4884. log.debug("App.on_tools_database() --> %s" % str(e))
  4885. return
  4886. # delete the absolute and relative position and messages in the infobar
  4887. self.ui.position_label.setText("")
  4888. # self.ui.rel_position_label.setText("")
  4889. # Switch plot_area to preferences page
  4890. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4891. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4892. self.tools_db_tab.ui_connect()
  4893. def on_tools_db_edited(self):
  4894. """
  4895. Executed whenever a tool is edited in Tools Database.
  4896. Will color the text of the Tools Database tab to Red color.
  4897. :return:
  4898. """
  4899. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4900. for idx in range(self.ui.plot_tab_area.count()):
  4901. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4902. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4903. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4904. self.tools_db_changed_flag = True
  4905. def on_geometry_tool_add_from_db_executed(self, tool):
  4906. """
  4907. Here add the tool from DB in the selected geometry object.
  4908. :return:
  4909. """
  4910. tool_from_db = deepcopy(tool)
  4911. obj = self.collection.get_active()
  4912. if isinstance(obj, GeometryObject):
  4913. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4914. # close the tab and delete it
  4915. for idx in range(self.ui.plot_tab_area.count()):
  4916. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4917. wdg = self.ui.plot_tab_area.widget(idx)
  4918. wdg.deleteLater()
  4919. self.ui.plot_tab_area.removeTab(idx)
  4920. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4921. else:
  4922. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4923. def on_plot_area_tab_closed(self, tab_obj_name):
  4924. """
  4925. Executed whenever a QTab is closed in the Plot Area.
  4926. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4927. :return:
  4928. """
  4929. if tab_obj_name == "preferences_tab":
  4930. self.preferencesUiManager.on_close_preferences_tab()
  4931. elif tab_obj_name == "database_tab":
  4932. # disconnect the signals from the table widget in tab
  4933. self.tools_db_tab.ui_disconnect()
  4934. if self.tools_db_changed_flag is True:
  4935. msgbox = QtWidgets.QMessageBox()
  4936. msgbox.setText(_("One or more Tools are edited.\n"
  4937. "Do you want to update the Tools Database?"))
  4938. msgbox.setWindowTitle(_("Save Tools Database"))
  4939. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4940. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4941. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4942. msgbox.setDefaultButton(bt_yes)
  4943. msgbox.exec_()
  4944. response = msgbox.clickedButton()
  4945. if response == bt_yes:
  4946. self.tools_db_tab.on_save_tools_db()
  4947. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4948. else:
  4949. self.tools_db_changed_flag = False
  4950. self.inform.emit('')
  4951. return
  4952. self.tools_db_tab.deleteLater()
  4953. elif tab_obj_name == "text_editor_tab":
  4954. self.toggle_codeeditor = False
  4955. elif tab_obj_name == "bookmarks_tab":
  4956. self.book_dialog_tab.rebuild_actions()
  4957. self.book_dialog_tab.deleteLater()
  4958. else:
  4959. return
  4960. # def on_plotarea_tab_closed(self, tab_idx):
  4961. # """
  4962. #
  4963. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4964. # :return:
  4965. # """
  4966. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4967. #
  4968. # if widget is not None:
  4969. # widget.deleteLater()
  4970. # self.ui.plot_tab_area.removeTab(tab_idx)
  4971. def on_flipy(self):
  4972. """
  4973. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4974. :return:
  4975. """
  4976. self.defaults.report_usage("on_flipy()")
  4977. obj_list = self.collection.get_selected()
  4978. xminlist = []
  4979. yminlist = []
  4980. xmaxlist = []
  4981. ymaxlist = []
  4982. if not obj_list:
  4983. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4984. else:
  4985. try:
  4986. # first get a bounding box to fit all
  4987. for obj in obj_list:
  4988. xmin, ymin, xmax, ymax = obj.bounds()
  4989. xminlist.append(xmin)
  4990. yminlist.append(ymin)
  4991. xmaxlist.append(xmax)
  4992. ymaxlist.append(ymax)
  4993. # get the minimum x,y and maximum x,y for all objects selected
  4994. xminimal = min(xminlist)
  4995. yminimal = min(yminlist)
  4996. xmaximal = max(xmaxlist)
  4997. ymaximal = max(ymaxlist)
  4998. px = 0.5 * (xminimal + xmaximal)
  4999. py = 0.5 * (yminimal + ymaximal)
  5000. # execute mirroring
  5001. for obj in obj_list:
  5002. obj.mirror('X', [px, py])
  5003. obj.plot()
  5004. self.object_changed.emit(obj)
  5005. self.inform.emit('[success] %s' %
  5006. _("Flip on Y axis done."))
  5007. except Exception as e:
  5008. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5009. return
  5010. def on_flipx(self):
  5011. """
  5012. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5013. :return:
  5014. """
  5015. self.defaults.report_usage("on_flipx()")
  5016. obj_list = self.collection.get_selected()
  5017. xminlist = []
  5018. yminlist = []
  5019. xmaxlist = []
  5020. ymaxlist = []
  5021. if not obj_list:
  5022. self.inform.emit('[WARNING_NOTCL] %s' %
  5023. _("No object selected to Flip on X axis."))
  5024. else:
  5025. try:
  5026. # first get a bounding box to fit all
  5027. for obj in obj_list:
  5028. xmin, ymin, xmax, ymax = obj.bounds()
  5029. xminlist.append(xmin)
  5030. yminlist.append(ymin)
  5031. xmaxlist.append(xmax)
  5032. ymaxlist.append(ymax)
  5033. # get the minimum x,y and maximum x,y for all objects selected
  5034. xminimal = min(xminlist)
  5035. yminimal = min(yminlist)
  5036. xmaximal = max(xmaxlist)
  5037. ymaximal = max(ymaxlist)
  5038. px = 0.5 * (xminimal + xmaximal)
  5039. py = 0.5 * (yminimal + ymaximal)
  5040. # execute mirroring
  5041. for obj in obj_list:
  5042. obj.mirror('Y', [px, py])
  5043. obj.plot()
  5044. self.object_changed.emit(obj)
  5045. self.inform.emit('[success] %s' %
  5046. _("Flip on X axis done."))
  5047. except Exception as e:
  5048. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5049. return
  5050. def on_rotate(self, silent=False, preset=None):
  5051. """
  5052. Executed when Options -> Rotate Selection menu entry is clicked.
  5053. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5054. :param preset: A value to be used as predefined angle for rotation.
  5055. :return:
  5056. """
  5057. self.defaults.report_usage("on_rotate()")
  5058. obj_list = self.collection.get_selected()
  5059. xminlist = []
  5060. yminlist = []
  5061. xmaxlist = []
  5062. ymaxlist = []
  5063. if not obj_list:
  5064. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5065. else:
  5066. if silent is False:
  5067. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5068. min=-360, max=360, decimals=4,
  5069. init_val=float(self.defaults['tools_transform_rotate']))
  5070. num, ok = rotatebox.get_value()
  5071. else:
  5072. num = preset
  5073. ok = True
  5074. if ok:
  5075. try:
  5076. # first get a bounding box to fit all
  5077. for obj in obj_list:
  5078. xmin, ymin, xmax, ymax = obj.bounds()
  5079. xminlist.append(xmin)
  5080. yminlist.append(ymin)
  5081. xmaxlist.append(xmax)
  5082. ymaxlist.append(ymax)
  5083. # get the minimum x,y and maximum x,y for all objects selected
  5084. xminimal = min(xminlist)
  5085. yminimal = min(yminlist)
  5086. xmaximal = max(xmaxlist)
  5087. ymaximal = max(ymaxlist)
  5088. px = 0.5 * (xminimal + xmaximal)
  5089. py = 0.5 * (yminimal + ymaximal)
  5090. for sel_obj in obj_list:
  5091. sel_obj.rotate(-float(num), point=(px, py))
  5092. sel_obj.plot()
  5093. self.object_changed.emit(sel_obj)
  5094. self.inform.emit('[success] %s' %
  5095. _("Rotation done."))
  5096. except Exception as e:
  5097. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5098. return
  5099. def on_skewx(self):
  5100. """
  5101. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5102. :return:
  5103. """
  5104. self.defaults.report_usage("on_skewx()")
  5105. obj_list = self.collection.get_selected()
  5106. xminlist = []
  5107. yminlist = []
  5108. if not obj_list:
  5109. self.inform.emit('[WARNING_NOTCL] %s' %
  5110. _("No object selected to Skew/Shear on X axis."))
  5111. else:
  5112. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5113. min=-360, max=360, decimals=4,
  5114. init_val=float(self.defaults['tools_transform_skew_x']))
  5115. num, ok = skewxbox.get_value()
  5116. if ok:
  5117. # first get a bounding box to fit all
  5118. for obj in obj_list:
  5119. xmin, ymin, xmax, ymax = obj.bounds()
  5120. xminlist.append(xmin)
  5121. yminlist.append(ymin)
  5122. # get the minimum x,y and maximum x,y for all objects selected
  5123. xminimal = min(xminlist)
  5124. yminimal = min(yminlist)
  5125. for obj in obj_list:
  5126. obj.skew(num, 0, point=(xminimal, yminimal))
  5127. obj.plot()
  5128. self.object_changed.emit(obj)
  5129. self.inform.emit('[success] %s' %
  5130. _("Skew on X axis done."))
  5131. def on_skewy(self):
  5132. """
  5133. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5134. :return:
  5135. """
  5136. self.defaults.report_usage("on_skewy()")
  5137. obj_list = self.collection.get_selected()
  5138. xminlist = []
  5139. yminlist = []
  5140. if not obj_list:
  5141. self.inform.emit('[WARNING_NOTCL] %s' %
  5142. _("No object selected to Skew/Shear on Y axis."))
  5143. else:
  5144. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5145. min=-360, max=360, decimals=4,
  5146. init_val=float(self.defaults['tools_transform_skew_y']))
  5147. num, ok = skewybox.get_value()
  5148. if ok:
  5149. # first get a bounding box to fit all
  5150. for obj in obj_list:
  5151. xmin, ymin, xmax, ymax = obj.bounds()
  5152. xminlist.append(xmin)
  5153. yminlist.append(ymin)
  5154. # get the minimum x,y and maximum x,y for all objects selected
  5155. xminimal = min(xminlist)
  5156. yminimal = min(yminlist)
  5157. for obj in obj_list:
  5158. obj.skew(0, num, point=(xminimal, yminimal))
  5159. obj.plot()
  5160. self.object_changed.emit(obj)
  5161. self.inform.emit('[success] %s' %
  5162. _("Skew on Y axis done."))
  5163. def on_plots_updated(self):
  5164. """
  5165. Callback used to report when the plots have changed.
  5166. Adjust axes and zooms to fit.
  5167. :return: None
  5168. """
  5169. if self.is_legacy is False:
  5170. self.plotcanvas.update()
  5171. else:
  5172. self.plotcanvas.auto_adjust_axes()
  5173. self.on_zoom_fit(None)
  5174. self.collection.update_view()
  5175. # self.inform.emit(_("Plots updated ..."))
  5176. def on_toolbar_replot(self):
  5177. """
  5178. Callback for toolbar button. Re-plots all objects.
  5179. :return: None
  5180. """
  5181. self.defaults.report_usage("on_toolbar_replot")
  5182. self.log.debug("on_toolbar_replot()")
  5183. try:
  5184. self.collection.get_active().read_form()
  5185. except AttributeError:
  5186. self.log.debug("on_toolbar_replot(): AttributeError")
  5187. pass
  5188. self.plot_all()
  5189. def on_row_activated(self, index):
  5190. if index.isValid():
  5191. if index.internalPointer().parent_item != self.collection.root_item:
  5192. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5193. self.collection.on_item_activated(index)
  5194. def on_row_selected(self, obj_name):
  5195. """
  5196. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5197. It mean we clicked outside of the items and deselected all
  5198. :param obj_name:
  5199. :return:
  5200. """
  5201. if obj_name == 'none':
  5202. for act in self.ui.menuobjects.actions():
  5203. act.setChecked(False)
  5204. return
  5205. # get the name of the selected objects and add them to a list
  5206. name_list = []
  5207. for obj in self.collection.get_selected():
  5208. name_list.append(obj.options['name'])
  5209. # set all actions as unchecked but the ones selected make them checked
  5210. for act in self.ui.menuobjects.actions():
  5211. act.setChecked(False)
  5212. if act.text() in name_list:
  5213. act.setChecked(True)
  5214. def on_collection_updated(self, obj, state, old_name):
  5215. """
  5216. Create a menu from the object loaded in the collection.
  5217. :param obj: object that was changed (added, deleted, renamed)
  5218. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5219. :param old_name: the old name of the object before the action that triggered this slot happened
  5220. :return: None
  5221. """
  5222. icon_files = {
  5223. "gerber": self.resource_location + "/flatcam_icon16.png",
  5224. "excellon": self.resource_location + "/drill16.png",
  5225. "cncjob": self.resource_location + "/cnc16.png",
  5226. "geometry": self.resource_location + "/geometry16.png",
  5227. "script": self.resource_location + "/script_new16.png",
  5228. "document": self.resource_location + "/notes16_1.png"
  5229. }
  5230. if state == 'append':
  5231. for act in self.ui.menuobjects.actions():
  5232. try:
  5233. act.triggered.disconnect()
  5234. except TypeError:
  5235. pass
  5236. self.ui.menuobjects.clear()
  5237. gerber_list = []
  5238. exc_list = []
  5239. cncjob_list = []
  5240. geo_list = []
  5241. script_list = []
  5242. doc_list = []
  5243. for name in self.collection.get_names():
  5244. obj_named = self.collection.get_by_name(name)
  5245. if obj_named.kind == 'gerber':
  5246. gerber_list.append(name)
  5247. elif obj_named.kind == 'excellon':
  5248. exc_list.append(name)
  5249. elif obj_named.kind == 'cncjob':
  5250. cncjob_list.append(name)
  5251. elif obj_named.kind == 'geometry':
  5252. geo_list.append(name)
  5253. elif obj_named.kind == 'script':
  5254. script_list.append(name)
  5255. elif obj_named.kind == 'document':
  5256. doc_list.append(name)
  5257. def add_act(o_name):
  5258. obj_for_icon = self.collection.get_by_name(o_name)
  5259. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5260. add_action.setCheckable(True)
  5261. add_action.setText(o_name)
  5262. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5263. add_action.triggered.connect(
  5264. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5265. self.collection.set_inactive(o_name))
  5266. self.ui.menuobjects.addAction(add_action)
  5267. for name in gerber_list:
  5268. add_act(name)
  5269. self.ui.menuobjects.addSeparator()
  5270. for name in exc_list:
  5271. add_act(name)
  5272. self.ui.menuobjects.addSeparator()
  5273. for name in cncjob_list:
  5274. add_act(name)
  5275. self.ui.menuobjects.addSeparator()
  5276. for name in geo_list:
  5277. add_act(name)
  5278. self.ui.menuobjects.addSeparator()
  5279. for name in script_list:
  5280. add_act(name)
  5281. self.ui.menuobjects.addSeparator()
  5282. for name in doc_list:
  5283. add_act(name)
  5284. self.ui.menuobjects.addSeparator()
  5285. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5286. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5287. _('Select All')
  5288. )
  5289. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5290. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5291. _('Deselect All')
  5292. )
  5293. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5294. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5295. elif state == 'delete':
  5296. for act in self.ui.menuobjects.actions():
  5297. if act.text() == obj.options['name']:
  5298. try:
  5299. act.triggered.disconnect()
  5300. except TypeError:
  5301. pass
  5302. self.ui.menuobjects.removeAction(act)
  5303. break
  5304. elif state == 'rename':
  5305. for act in self.ui.menuobjects.actions():
  5306. if act.text() == old_name:
  5307. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5308. add_action.setText(obj.options['name'])
  5309. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5310. add_action.triggered.connect(
  5311. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5312. self.collection.set_inactive(obj.options['name']))
  5313. self.ui.menuobjects.insertAction(act, add_action)
  5314. try:
  5315. act.triggered.disconnect()
  5316. except TypeError:
  5317. pass
  5318. self.ui.menuobjects.removeAction(act)
  5319. break
  5320. elif state == 'delete_all':
  5321. for act in self.ui.menuobjects.actions():
  5322. try:
  5323. act.triggered.disconnect()
  5324. except TypeError:
  5325. pass
  5326. self.ui.menuobjects.clear()
  5327. self.ui.menuobjects.addSeparator()
  5328. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5329. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5330. _('Select All')
  5331. )
  5332. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5333. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5334. _('Deselect All')
  5335. )
  5336. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5337. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5338. def on_objects_selection(self, on_off):
  5339. obj_list = self.collection.get_names()
  5340. if on_off is True:
  5341. self.collection.set_all_active()
  5342. for act in self.ui.menuobjects.actions():
  5343. try:
  5344. act.setChecked(True)
  5345. except Exception:
  5346. pass
  5347. if obj_list:
  5348. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5349. else:
  5350. self.collection.set_all_inactive()
  5351. for act in self.ui.menuobjects.actions():
  5352. try:
  5353. act.setChecked(False)
  5354. except Exception:
  5355. pass
  5356. if obj_list:
  5357. self.inform.emit('%s' % _("Objects selection is cleared."))
  5358. else:
  5359. self.inform.emit('')
  5360. def grid_status(self):
  5361. return True if self.ui.grid_snap_btn.isChecked() else False
  5362. def populate_cmenu_grids(self):
  5363. units = self.defaults['units'].lower()
  5364. # for act in self.ui.cmenu_gridmenu.actions():
  5365. # act.triggered.disconnect()
  5366. self.ui.cmenu_gridmenu.clear()
  5367. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5368. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5369. _("Grid On/Off"))
  5370. grid_toggle.setCheckable(True)
  5371. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5372. self.ui.cmenu_gridmenu.addSeparator()
  5373. for grid in sorted_list:
  5374. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5375. "%s" % str(grid))
  5376. action.triggered.connect(self.set_grid)
  5377. self.ui.cmenu_gridmenu.addSeparator()
  5378. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5379. _("Add"))
  5380. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5381. _("Delete"))
  5382. grid_add.triggered.connect(self.on_grid_add)
  5383. grid_delete.triggered.connect(self.on_grid_delete)
  5384. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5385. def set_grid(self):
  5386. menu_action = self.sender()
  5387. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5388. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5389. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5390. def on_grid_add(self):
  5391. # ## Current application units in lower Case
  5392. units = self.defaults['units'].lower()
  5393. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5394. text=_('Enter a Grid Value:'),
  5395. min=0.0000, max=99.9999, decimals=4)
  5396. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5397. val, ok = grid_add_popup.get_value()
  5398. if ok:
  5399. if float(val) == 0:
  5400. self.inform.emit('[WARNING_NOTCL] %s' %
  5401. _("Please enter a grid value with non-zero value, in Float format."))
  5402. return
  5403. else:
  5404. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5405. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5406. self.inform.emit('[success] %s...' % _("New Grid added"))
  5407. else:
  5408. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5409. else:
  5410. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5411. def on_grid_delete(self):
  5412. # ## Current application units in lower Case
  5413. units = self.defaults['units'].lower()
  5414. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5415. text='Enter a Grid Value:',
  5416. min=0.0000, max=99.9999, decimals=4)
  5417. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5418. val, ok = grid_del_popup.get_value()
  5419. if ok:
  5420. if float(val) == 0:
  5421. self.inform.emit('[WARNING_NOTCL] %s' %
  5422. _("Please enter a grid value with non-zero value, in Float format."))
  5423. return
  5424. else:
  5425. try:
  5426. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5427. except ValueError:
  5428. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5429. return
  5430. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5431. else:
  5432. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5433. def on_shortcut_list(self):
  5434. self.defaults.report_usage("on_shortcut_list()")
  5435. # add the tab if it was closed
  5436. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5437. # delete the absolute and relative position and messages in the infobar
  5438. self.ui.position_label.setText("")
  5439. # self.ui.rel_position_label.setText("")
  5440. # Switch plot_area to preferences page
  5441. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5442. # self.ui.show()
  5443. def on_select_tab(self, name):
  5444. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5445. if self.ui.splitter.sizes()[0] == 0:
  5446. self.ui.splitter.setSizes([1, 1])
  5447. else:
  5448. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5449. self.ui.splitter.setSizes([0, 1])
  5450. if name == 'project':
  5451. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5452. elif name == 'selected':
  5453. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5454. elif name == 'tool':
  5455. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5456. def on_copy_name(self):
  5457. self.defaults.report_usage("on_copy_name()")
  5458. obj = self.collection.get_active()
  5459. try:
  5460. name = obj.options["name"]
  5461. except AttributeError:
  5462. log.debug("on_copy_name() --> No object selected to copy it's name")
  5463. self.inform.emit('[WARNING_NOTCL]%s' %
  5464. _(" No object selected to copy it's name"))
  5465. return
  5466. self.clipboard.setText(name)
  5467. self.inform.emit(_("Name copied on clipboard ..."))
  5468. def on_mouse_click_over_plot(self, event):
  5469. """
  5470. Default actions are:
  5471. :param event: Contains information about the event, like which button
  5472. was clicked, the pixel coordinates and the axes coordinates.
  5473. :return: None
  5474. """
  5475. self.pos = []
  5476. if self.is_legacy is False:
  5477. event_pos = event.pos
  5478. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5479. # # Set the mouse button for panning
  5480. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5481. else:
  5482. event_pos = (event.xdata, event.ydata)
  5483. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5484. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5485. # So it can receive key presses
  5486. self.plotcanvas.native.setFocus()
  5487. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5488. if self.grid_status():
  5489. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5490. else:
  5491. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5492. try:
  5493. if event.button == 1:
  5494. # Reset here the relative coordinates so there is a new reference on the click position
  5495. if self.rel_point1 is None:
  5496. self.rel_point1 = self.pos
  5497. else:
  5498. self.rel_point2 = copy(self.rel_point1)
  5499. self.rel_point1 = self.pos
  5500. self.on_mouse_move_over_plot(event, origin_click=True)
  5501. except Exception as e:
  5502. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5503. def on_mouse_double_click_over_plot(self, event):
  5504. if event.button == 1:
  5505. self.doubleclick = True
  5506. def on_mouse_move_over_plot(self, event, origin_click=None):
  5507. """
  5508. Callback for the mouse motion event over the plot.
  5509. :param event: Contains information about the event.
  5510. :param origin_click
  5511. :return: None
  5512. """
  5513. if self.is_legacy is False:
  5514. event_pos = event.pos
  5515. if self.defaults["global_pan_button"] == '2':
  5516. pan_button = 2
  5517. else:
  5518. pan_button = 3
  5519. self.event_is_dragging = event.is_dragging
  5520. else:
  5521. event_pos = (event.xdata, event.ydata)
  5522. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5523. if self.defaults["global_pan_button"] == '2':
  5524. pan_button = 3
  5525. else:
  5526. pan_button = 2
  5527. self.event_is_dragging = self.plotcanvas.is_dragging
  5528. # So it can receive key presses but not when the Tcl Shell is active
  5529. if not self.ui.shell_dock.isVisible():
  5530. if not self.plotcanvas.native.hasFocus():
  5531. self.plotcanvas.native.setFocus()
  5532. self.pos_jump = event_pos
  5533. self.ui.popMenu.mouse_is_panning = False
  5534. if origin_click is None:
  5535. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5536. if event.button == pan_button and self.event_is_dragging == 1:
  5537. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5538. if self.ui.popMenu.popup_active:
  5539. self.ui.popMenu.popup_active = False
  5540. return
  5541. self.ui.popMenu.mouse_is_panning = True
  5542. return
  5543. if self.rel_point1 is not None:
  5544. try: # May fail in case mouse not within axes
  5545. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5546. if pos_canvas[0] is None or pos_canvas[1] is None:
  5547. return
  5548. if self.grid_status():
  5549. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5550. # Update cursor
  5551. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5552. symbol='++', edge_color=self.cursor_color_3D,
  5553. edge_width=self.defaults["global_cursor_width"],
  5554. size=self.defaults["global_cursor_size"])
  5555. else:
  5556. pos = (pos_canvas[0], pos_canvas[1])
  5557. self.dx = pos[0] - float(self.rel_point1[0])
  5558. self.dy = pos[1] - float(self.rel_point1[1])
  5559. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5560. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5561. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5562. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5563. units = self.defaults["units"].lower()
  5564. self.plotcanvas.text_hud.text = \
  5565. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5566. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5567. self.mouse = [pos[0], pos[1]]
  5568. # if the mouse is moved and the LMB is clicked then the action is a selection
  5569. if self.event_is_dragging == 1 and event.button == 1:
  5570. self.delete_selection_shape()
  5571. if self.dx < 0:
  5572. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5573. face_color=self.defaults['global_alt_sel_fill'])
  5574. self.selection_type = False
  5575. elif self.dx >= 0:
  5576. self.draw_moving_selection_shape(self.pos, pos)
  5577. self.selection_type = True
  5578. else:
  5579. self.selection_type = None
  5580. else:
  5581. self.selection_type = None
  5582. # hover effect - enabled in Preferences -> General -> GUI Settings
  5583. if self.defaults['global_hover']:
  5584. for obj in self.collection.get_list():
  5585. try:
  5586. # select the object(s) only if it is enabled (plotted)
  5587. if obj.options['plot']:
  5588. if obj not in self.collection.get_selected():
  5589. poly_obj = Polygon(
  5590. [(obj.options['xmin'], obj.options['ymin']),
  5591. (obj.options['xmax'], obj.options['ymin']),
  5592. (obj.options['xmax'], obj.options['ymax']),
  5593. (obj.options['xmin'], obj.options['ymax'])]
  5594. )
  5595. if Point(pos).within(poly_obj):
  5596. if obj.isHovering is False:
  5597. obj.isHovering = True
  5598. obj.notHovering = True
  5599. # create the selection box around the selected object
  5600. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5601. else:
  5602. if obj.notHovering is True:
  5603. obj.notHovering = False
  5604. obj.isHovering = False
  5605. self.delete_hover_shape()
  5606. except Exception:
  5607. # the Exception here will happen if we try to select on screen and we have an
  5608. # newly (and empty) just created Geometry or Excellon object that do not have the
  5609. # xmin, xmax, ymin, ymax options.
  5610. # In this case poly_obj creation (see above) will fail
  5611. pass
  5612. except Exception as e:
  5613. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5614. self.ui.position_label.setText("")
  5615. # self.ui.rel_position_label.setText("")
  5616. self.mouse = None
  5617. def on_mouse_click_release_over_plot(self, event):
  5618. """
  5619. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5620. and has been registered in ''self.__init__()''.
  5621. :param event: contains information about the event.
  5622. :return:
  5623. """
  5624. if self.is_legacy is False:
  5625. event_pos = event.pos
  5626. right_button = 2
  5627. else:
  5628. event_pos = (event.xdata, event.ydata)
  5629. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5630. right_button = 3
  5631. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5632. if self.grid_status():
  5633. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5634. else:
  5635. pos = (pos_canvas[0], pos_canvas[1])
  5636. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5637. # canvas menu
  5638. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5639. self.ui.popMenu.mouse_is_panning = False
  5640. self.cursor = QtGui.QCursor()
  5641. self.populate_cmenu_grids()
  5642. self.ui.popMenu.popup(self.cursor.pos())
  5643. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5644. # selection and then select a type of selection ("enclosing" or "touching")
  5645. if event.button == 1: # left click
  5646. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5647. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5648. if modifiers == QtCore.Qt.ShiftModifier:
  5649. # do not auto open the Project Tab
  5650. self.click_noproject = True
  5651. self.clipboard.setText(
  5652. self.defaults["global_point_clipboard_format"] %
  5653. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5654. )
  5655. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5656. return
  5657. if self.doubleclick is True:
  5658. self.doubleclick = False
  5659. if self.collection.get_selected():
  5660. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5661. if self.ui.splitter.sizes()[0] == 0:
  5662. self.ui.splitter.setSizes([1, 1])
  5663. try:
  5664. # delete the selection shape(S) as it may be in the way
  5665. self.delete_selection_shape()
  5666. self.delete_hover_shape()
  5667. except Exception as e:
  5668. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5669. return
  5670. else:
  5671. # WORKAROUND for LEGACY MODE
  5672. if self.is_legacy is True:
  5673. # if there is no move on canvas then we have no dragging selection
  5674. if self.dx == 0 or self.dy == 0:
  5675. self.selection_type = None
  5676. if self.selection_type is not None:
  5677. try:
  5678. self.selection_area_handler(self.pos, pos, self.selection_type)
  5679. self.selection_type = None
  5680. except Exception as e:
  5681. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5682. return
  5683. else:
  5684. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5685. if key_modifier == QtCore.Qt.ShiftModifier:
  5686. mod_key = 'Shift'
  5687. elif key_modifier == QtCore.Qt.ControlModifier:
  5688. mod_key = 'Control'
  5689. else:
  5690. mod_key = None
  5691. try:
  5692. if self.command_active is None:
  5693. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5694. # deselect, and if it's not selected then it will be selected
  5695. # If there is no active command (self.command_active is None) then we check if we clicked
  5696. # on a object by checking the bounding limits against mouse click position
  5697. if mod_key == self.defaults["global_mselect_key"]:
  5698. self.select_objects(key='multisel')
  5699. else:
  5700. # If there is no active command (self.command_active is None) then we check if
  5701. # we clicked on a object by checking the bounding limits against mouse click position
  5702. self.select_objects()
  5703. self.delete_hover_shape()
  5704. except Exception as e:
  5705. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5706. return
  5707. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5708. """
  5709. :param start_pos: mouse position when the selection LMB click was done
  5710. :param end_pos: mouse position when the left mouse button is released
  5711. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5712. :return:
  5713. """
  5714. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5715. # delete previous selection shape
  5716. self.delete_selection_shape()
  5717. # make all objects inactive
  5718. self.collection.set_all_inactive()
  5719. for obj in self.collection.get_list():
  5720. try:
  5721. # select the object(s) only if it is enabled (plotted)
  5722. if obj.options['plot']:
  5723. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5724. (obj.options['xmax'], obj.options['ymin']),
  5725. (obj.options['xmax'], obj.options['ymax']),
  5726. (obj.options['xmin'], obj.options['ymax'])])
  5727. if sel_type is True:
  5728. if poly_obj.within(poly_selection):
  5729. # create the selection box around the selected object
  5730. if self.defaults['global_selection_shape'] is True:
  5731. self.draw_selection_shape(obj)
  5732. self.collection.set_active(obj.options['name'])
  5733. else:
  5734. if poly_selection.intersects(poly_obj):
  5735. # create the selection box around the selected object
  5736. if self.defaults['global_selection_shape'] is True:
  5737. self.draw_selection_shape(obj)
  5738. self.collection.set_active(obj.options['name'])
  5739. obj.selection_shape_drawn = True
  5740. except Exception as e:
  5741. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5742. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5743. # In this case poly_obj creation (see above) will fail
  5744. log.debug("App.selection_area_handler() --> %s" % str(e))
  5745. def select_objects(self, key=None):
  5746. """
  5747. Will select objects clicked on canvas
  5748. :param key: for future use in cumulative selection
  5749. :return:
  5750. """
  5751. # list where we store the overlapped objects under our mouse left click position
  5752. if key is None:
  5753. self.objects_under_the_click_list = []
  5754. # Populate the list with the overlapped objects on the click position
  5755. curr_x, curr_y = self.pos
  5756. for obj in self.all_objects_list:
  5757. # ScriptObject and DocumentObject objects can't be selected
  5758. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5759. continue
  5760. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5761. continue
  5762. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5763. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5764. if obj.options['name'] not in self.objects_under_the_click_list:
  5765. if obj.options['plot']:
  5766. # add objects to the objects_under_the_click list only if the object is plotted
  5767. # (active and not disabled)
  5768. self.objects_under_the_click_list.append(obj.options['name'])
  5769. try:
  5770. if self.objects_under_the_click_list:
  5771. curr_sel_obj = self.collection.get_active()
  5772. # case when there is only an object under the click and we toggle it
  5773. if len(self.objects_under_the_click_list) == 1:
  5774. if curr_sel_obj is None:
  5775. self.collection.set_active(self.objects_under_the_click_list[0])
  5776. curr_sel_obj = self.collection.get_active()
  5777. # create the selection box around the selected object
  5778. if self.defaults['global_selection_shape'] is True:
  5779. self.draw_selection_shape(curr_sel_obj)
  5780. curr_sel_obj.selection_shape_drawn = True
  5781. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5782. self.on_objects_selection(False)
  5783. self.delete_selection_shape()
  5784. curr_sel_obj.selection_shape_drawn = False
  5785. self.collection.set_active(self.objects_under_the_click_list[0])
  5786. curr_sel_obj = self.collection.get_active()
  5787. # create the selection box around the selected object
  5788. if self.defaults['global_selection_shape'] is True:
  5789. self.draw_selection_shape(curr_sel_obj)
  5790. curr_sel_obj.selection_shape_drawn = True
  5791. self.selected_message(curr_sel_obj=curr_sel_obj)
  5792. elif curr_sel_obj.selection_shape_drawn is False:
  5793. if self.defaults['global_selection_shape'] is True:
  5794. self.draw_selection_shape(curr_sel_obj)
  5795. curr_sel_obj.selection_shape_drawn = True
  5796. else:
  5797. self.on_objects_selection(False)
  5798. self.delete_selection_shape()
  5799. if self.call_source != 'app':
  5800. self.call_source = 'app'
  5801. self.selected_message(curr_sel_obj=curr_sel_obj)
  5802. else:
  5803. # If there is no selected object
  5804. # make active the first element of the overlapped objects list
  5805. if self.collection.get_active() is None:
  5806. self.collection.set_active(self.objects_under_the_click_list[0])
  5807. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5808. name_sel_obj = self.collection.get_active().options['name']
  5809. # In case that there is a selected object but it is not in the overlapped object list
  5810. # make that object inactive and activate the first element in the overlapped object list
  5811. if name_sel_obj not in self.objects_under_the_click_list:
  5812. self.collection.set_inactive(name_sel_obj)
  5813. name_sel_obj = self.objects_under_the_click_list[0]
  5814. self.collection.set_active(name_sel_obj)
  5815. else:
  5816. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5817. self.collection.set_all_inactive()
  5818. self.collection.set_active(
  5819. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5820. curr_sel_obj = self.collection.get_active()
  5821. # delete the possible selection box around a possible selected object
  5822. self.delete_selection_shape()
  5823. curr_sel_obj.selection_shape_drawn = False
  5824. # create the selection box around the selected object
  5825. if self.defaults['global_selection_shape'] is True:
  5826. self.draw_selection_shape(curr_sel_obj)
  5827. curr_sel_obj.selection_shape_drawn = True
  5828. self.selected_message(curr_sel_obj=curr_sel_obj)
  5829. else:
  5830. # deselect everything
  5831. self.on_objects_selection(False)
  5832. # delete the possible selection box around a possible selected object
  5833. self.delete_selection_shape()
  5834. for o in self.collection.get_list():
  5835. o.selection_shape_drawn = False
  5836. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5837. # only when working on App
  5838. if self.call_source == 'app':
  5839. if self.click_noproject is False:
  5840. # if the Tool Tab is in focus don't change focus to Project Tab
  5841. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5842. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5843. else:
  5844. # restore auto open the Project Tab
  5845. self.click_noproject = False
  5846. # delete any text in the status bar, implicitly the last object name that was selected
  5847. # self.inform.emit("")
  5848. else:
  5849. self.call_source = 'app'
  5850. except Exception as e:
  5851. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5852. def selected_message(self, curr_sel_obj):
  5853. if curr_sel_obj:
  5854. if curr_sel_obj.kind == 'gerber':
  5855. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5856. color='green',
  5857. name=str(curr_sel_obj.options['name']),
  5858. tx=_("selected"))
  5859. )
  5860. elif curr_sel_obj.kind == 'excellon':
  5861. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5862. color='brown',
  5863. name=str(curr_sel_obj.options['name']),
  5864. tx=_("selected"))
  5865. )
  5866. elif curr_sel_obj.kind == 'cncjob':
  5867. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5868. color='blue',
  5869. name=str(curr_sel_obj.options['name']),
  5870. tx=_("selected"))
  5871. )
  5872. elif curr_sel_obj.kind == 'geometry':
  5873. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5874. color='red',
  5875. name=str(curr_sel_obj.options['name']),
  5876. tx=_("selected"))
  5877. )
  5878. def delete_hover_shape(self):
  5879. self.hover_shapes.clear()
  5880. self.hover_shapes.redraw()
  5881. def draw_hover_shape(self, sel_obj, color=None):
  5882. """
  5883. :param sel_obj: The object for which the hover shape must be drawn
  5884. :param color: The color of the hover shape
  5885. :return: None
  5886. """
  5887. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5888. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5889. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5890. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5891. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5892. if self.defaults['units'].upper() == 'MM':
  5893. hover_rect = hover_rect.buffer(-0.1)
  5894. hover_rect = hover_rect.buffer(0.2)
  5895. else:
  5896. hover_rect = hover_rect.buffer(-0.00393)
  5897. hover_rect = hover_rect.buffer(0.00787)
  5898. # if color:
  5899. # face = Color(color)
  5900. # face.alpha = 0.2
  5901. # outline = Color(color, alpha=0.8)
  5902. # else:
  5903. # face = Color(self.defaults['global_sel_fill'])
  5904. # face.alpha = 0.2
  5905. # outline = self.defaults['global_sel_line']
  5906. if color:
  5907. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5908. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5909. else:
  5910. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5911. outline = self.defaults['global_sel_line']
  5912. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5913. if self.is_legacy is True:
  5914. self.hover_shapes.redraw()
  5915. def delete_selection_shape(self):
  5916. self.move_tool.sel_shapes.clear()
  5917. self.move_tool.sel_shapes.redraw()
  5918. def draw_selection_shape(self, sel_obj, color=None):
  5919. """
  5920. Will draw a selection shape around the selected object.
  5921. :param sel_obj: The object for which the selection shape must be drawn
  5922. :param color: The color for the selection shape.
  5923. :return: None
  5924. """
  5925. if sel_obj is None:
  5926. return
  5927. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5928. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5929. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5930. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5931. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5932. if self.defaults['units'].upper() == 'MM':
  5933. sel_rect = sel_rect.buffer(-0.1)
  5934. sel_rect = sel_rect.buffer(0.2)
  5935. else:
  5936. sel_rect = sel_rect.buffer(-0.00393)
  5937. sel_rect = sel_rect.buffer(0.00787)
  5938. if color:
  5939. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5940. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5941. else:
  5942. if self.is_legacy is False:
  5943. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5944. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5945. else:
  5946. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5947. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5948. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5949. color=outline,
  5950. face_color=face,
  5951. update=True,
  5952. layer=0,
  5953. tolerance=None))
  5954. if self.is_legacy is True:
  5955. self.move_tool.sel_shapes.redraw()
  5956. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5957. """
  5958. Will draw a selection shape when dragging mouse on canvas.
  5959. :param old_coords: Old coordinates
  5960. :param coords: New coordinates
  5961. :param kwargs: Keyword arguments
  5962. :return:
  5963. """
  5964. if 'color' in kwargs:
  5965. color = kwargs['color']
  5966. else:
  5967. color = self.defaults['global_sel_line']
  5968. if 'face_color' in kwargs:
  5969. face_color = kwargs['face_color']
  5970. else:
  5971. face_color = self.defaults['global_sel_fill']
  5972. if 'face_alpha' in kwargs:
  5973. face_alpha = kwargs['face_alpha']
  5974. else:
  5975. face_alpha = 0.3
  5976. x0, y0 = old_coords
  5977. x1, y1 = coords
  5978. pt1 = (x0, y0)
  5979. pt2 = (x1, y0)
  5980. pt3 = (x1, y1)
  5981. pt4 = (x0, y1)
  5982. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5983. # color_t = Color(face_color)
  5984. # color_t.alpha = face_alpha
  5985. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5986. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5987. layer=0, tolerance=None)
  5988. if self.is_legacy is True:
  5989. self.move_tool.sel_shapes.redraw()
  5990. def on_file_new_click(self):
  5991. """
  5992. Callback for menu item File -> New.
  5993. Executed on clicking the Menu -> File -> New Project
  5994. :return:
  5995. """
  5996. if self.collection.get_list() and self.should_we_save:
  5997. msgbox = QtWidgets.QMessageBox()
  5998. # msgbox.setText("<B>Save changes ...</B>")
  5999. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6000. "Creating a New project will delete them.\n"
  6001. "Do you want to Save the project?"))
  6002. msgbox.setWindowTitle(_("Save changes"))
  6003. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6004. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6005. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6006. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6007. msgbox.setDefaultButton(bt_yes)
  6008. msgbox.exec_()
  6009. response = msgbox.clickedButton()
  6010. if response == bt_yes:
  6011. self.on_file_saveprojectas()
  6012. elif response == bt_cancel:
  6013. return
  6014. elif response == bt_no:
  6015. self.on_file_new()
  6016. else:
  6017. self.on_file_new()
  6018. self.inform.emit('[success] %s...' % _("New Project created"))
  6019. def on_file_new(self, cli=None):
  6020. """
  6021. Returns the application to its startup state. This method is thread-safe.
  6022. :param cli: Boolean. If True this method was run from command line
  6023. :return: None
  6024. """
  6025. self.defaults.report_usage("on_file_new")
  6026. # Remove everything from memory
  6027. App.log.debug("on_file_new()")
  6028. # close any editor that might be open
  6029. if self.call_source != 'app':
  6030. self.editor2object(cleanup=True)
  6031. # ## EDITOR section
  6032. self.geo_editor = FlatCAMGeoEditor(self)
  6033. self.exc_editor = FlatCAMExcEditor(self)
  6034. self.grb_editor = FlatCAMGrbEditor(self)
  6035. # Clear pool
  6036. self.clear_pool()
  6037. for obj in self.collection.get_list():
  6038. # delete shapes left drawn from mark shape_collections, if any
  6039. if isinstance(obj, GerberObject):
  6040. try:
  6041. for el in obj.mark_shapes:
  6042. obj.mark_shapes[el].clear(update=True)
  6043. obj.mark_shapes[el].enabled = False
  6044. del el
  6045. except AttributeError:
  6046. pass
  6047. # also delete annotation shapes, if any
  6048. elif isinstance(obj, CNCJobObject):
  6049. try:
  6050. obj.text_col.enabled = False
  6051. del obj.text_col
  6052. obj.annotation.clear(update=True)
  6053. del obj.annotation
  6054. except AttributeError:
  6055. pass
  6056. # delete the exclusion areas
  6057. self.exc_areas.clear_shapes()
  6058. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6059. self.shell.init_tcl()
  6060. # delete any selection shape on canvas
  6061. self.delete_selection_shape()
  6062. # delete all FlatCAM objects
  6063. self.collection.delete_all()
  6064. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6065. self.setup_component_editor()
  6066. # Clear project filename
  6067. self.project_filename = None
  6068. # Load the application defaults
  6069. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6070. # Re-fresh project options
  6071. self.on_options_app2project()
  6072. # Init FlatCAMTools
  6073. self.init_tools()
  6074. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6075. if cli is None:
  6076. # we need to go in reverse because once we remove a tab then the index changes
  6077. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6078. # and so on. Therefore the deletion should be done in reverse
  6079. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6080. for index in range(wdg_count, -1, -1):
  6081. try:
  6082. self.ui.plot_tab_area.closeTab(index)
  6083. except Exception as e:
  6084. log.debug("App.on_file_new() --> %s" % str(e))
  6085. # # And then add again the Plot Area
  6086. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6087. self.ui.plot_tab_area.protectTab(0)
  6088. # take the focus of the Notebook on Project Tab.
  6089. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6090. self.set_ui_title(name=_("New Project - Not saved"))
  6091. def obj_properties(self):
  6092. """
  6093. Will launch the object Properties Tool
  6094. :return:
  6095. """
  6096. self.defaults.report_usage("obj_properties()")
  6097. self.properties_tool.run(toggle=False)
  6098. def on_project_context_save(self):
  6099. """
  6100. Wrapper, will save the object function of it's type
  6101. :return:
  6102. """
  6103. obj = self.collection.get_active()
  6104. if type(obj) == GeometryObject:
  6105. self.on_file_exportdxf()
  6106. elif type(obj) == ExcellonObject:
  6107. self.on_file_saveexcellon()
  6108. elif type(obj) == CNCJobObject:
  6109. obj.on_exportgcode_button_click()
  6110. elif type(obj) == GerberObject:
  6111. self.on_file_savegerber()
  6112. elif type(obj) == ScriptObject:
  6113. self.on_file_savescript()
  6114. elif type(obj) == DocumentObject:
  6115. self.on_file_savedocument()
  6116. def obj_move(self):
  6117. """
  6118. Callback for the Move menu entry in various Context Menu's.
  6119. :return:
  6120. """
  6121. self.defaults.report_usage("obj_move()")
  6122. self.move_tool.run(toggle=False)
  6123. def on_fileopengerber(self, signal, name=None):
  6124. """
  6125. File menu callback for opening a Gerber.
  6126. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6127. :param name:
  6128. :return: None
  6129. """
  6130. self.defaults.report_usage("on_fileopengerber")
  6131. App.log.debug("on_fileopengerber()")
  6132. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6133. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6134. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6135. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6136. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6137. "*.mil);;" \
  6138. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6139. "Allegro Files (*.art);;" \
  6140. "Mentor Files (*.pho *.gdo);;" \
  6141. "All Files (*.*)"
  6142. if name is None:
  6143. try:
  6144. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6145. directory=self.get_last_folder(),
  6146. filter=_filter_)
  6147. except TypeError:
  6148. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6149. filenames = [str(filename) for filename in filenames]
  6150. else:
  6151. filenames = [name]
  6152. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6153. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6154. _("Opening Gerber file.")),
  6155. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6156. color=QtGui.QColor("gray"))
  6157. if len(filenames) == 0:
  6158. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6159. else:
  6160. for filename in filenames:
  6161. if filename != '':
  6162. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6163. def on_fileopenexcellon(self, signal, name=None):
  6164. """
  6165. File menu callback for opening an Excellon file.
  6166. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6167. :param name:
  6168. :return: None
  6169. """
  6170. self.defaults.report_usage("on_fileopenexcellon")
  6171. App.log.debug("on_fileopenexcellon()")
  6172. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6173. "All Files (*.*)"
  6174. if name is None:
  6175. try:
  6176. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6177. directory=self.get_last_folder(),
  6178. filter=_filter_)
  6179. except TypeError:
  6180. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6181. filenames = [str(filename) for filename in filenames]
  6182. else:
  6183. filenames = [str(name)]
  6184. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6185. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6186. _("Opening Excellon file.")),
  6187. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6188. color=QtGui.QColor("gray"))
  6189. if len(filenames) == 0:
  6190. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6191. else:
  6192. for filename in filenames:
  6193. if filename != '':
  6194. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6195. def on_fileopengcode(self, signal, name=None):
  6196. """
  6197. File menu call back for opening gcode.
  6198. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6199. :param name:
  6200. :return:
  6201. """
  6202. self.defaults.report_usage("on_fileopengcode")
  6203. App.log.debug("on_fileopengcode()")
  6204. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6205. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6206. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6207. "All Files (*.*)"
  6208. if name is None:
  6209. try:
  6210. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6211. directory=self.get_last_folder(),
  6212. filter=_filter_)
  6213. except TypeError:
  6214. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6215. filenames = [str(filename) for filename in filenames]
  6216. else:
  6217. filenames = [name]
  6218. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6219. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6220. _("Opening G-Code file.")),
  6221. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6222. color=QtGui.QColor("gray"))
  6223. if len(filenames) == 0:
  6224. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6225. else:
  6226. for filename in filenames:
  6227. if filename != '':
  6228. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6229. def on_file_openproject(self, signal):
  6230. """
  6231. File menu callback for opening a project.
  6232. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6233. :return: None
  6234. """
  6235. self.defaults.report_usage("on_file_openproject")
  6236. App.log.debug("on_file_openproject()")
  6237. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6238. try:
  6239. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6240. directory=self.get_last_folder(), filter=_filter_)
  6241. except TypeError:
  6242. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6243. # The Qt methods above will return a QString which can cause problems later.
  6244. # So far json.dump() will fail to serialize it.
  6245. # TODO: Improve the serialization methods and remove this fix.
  6246. filename = str(filename)
  6247. if filename == "":
  6248. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6249. else:
  6250. # self.worker_task.emit({'fcn': self.open_project,
  6251. # 'params': [filename]})
  6252. # The above was failing because open_project() is not
  6253. # thread safe. The new_project()
  6254. self.open_project(filename)
  6255. def on_fileopenhpgl2(self, signal, name=None):
  6256. """
  6257. File menu callback for opening a HPGL2.
  6258. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6259. :param name:
  6260. :return: None
  6261. """
  6262. self.defaults.report_usage("on_fileopenhpgl2")
  6263. App.log.debug("on_fileopenhpgl2()")
  6264. _filter_ = "HPGL2 Files (*.plt);;" \
  6265. "All Files (*.*)"
  6266. if name is None:
  6267. try:
  6268. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6269. directory=self.get_last_folder(),
  6270. filter=_filter_)
  6271. except TypeError:
  6272. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6273. filenames = [str(filename) for filename in filenames]
  6274. else:
  6275. filenames = [name]
  6276. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6277. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6278. _("Opening HPGL2 file.")),
  6279. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6280. color=QtGui.QColor("gray"))
  6281. if len(filenames) == 0:
  6282. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6283. else:
  6284. for filename in filenames:
  6285. if filename != '':
  6286. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6287. def on_file_openconfig(self, signal):
  6288. """
  6289. File menu callback for opening a config file.
  6290. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6291. :return: None
  6292. """
  6293. self.defaults.report_usage("on_file_openconfig")
  6294. App.log.debug("on_file_openconfig()")
  6295. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6296. try:
  6297. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6298. directory=self.data_path, filter=_filter_)
  6299. except TypeError:
  6300. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6301. filter=_filter_)
  6302. if filename == "":
  6303. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6304. else:
  6305. self.open_config_file(filename)
  6306. def on_file_exportsvg(self):
  6307. """
  6308. Callback for menu item File->Export SVG.
  6309. :return: None
  6310. """
  6311. self.defaults.report_usage("on_file_exportsvg")
  6312. App.log.debug("on_file_exportsvg()")
  6313. obj = self.collection.get_active()
  6314. if obj is None:
  6315. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6316. msg = _("Please Select a Geometry object to export")
  6317. msgbox = QtWidgets.QMessageBox()
  6318. msgbox.setInformativeText(msg)
  6319. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6320. msgbox.setDefaultButton(bt_ok)
  6321. msgbox.exec_()
  6322. return
  6323. # Check for more compatible types and add as required
  6324. if (not isinstance(obj, GeometryObject)
  6325. and not isinstance(obj, GerberObject)
  6326. and not isinstance(obj, CNCJobObject)
  6327. and not isinstance(obj, ExcellonObject)):
  6328. msg = '[ERROR_NOTCL] %s' % \
  6329. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6330. msgbox = QtWidgets.QMessageBox()
  6331. msgbox.setInformativeText(msg)
  6332. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6333. msgbox.setDefaultButton(bt_ok)
  6334. msgbox.exec_()
  6335. return
  6336. name = obj.options["name"]
  6337. _filter = "SVG File (*.svg);;All Files (*.*)"
  6338. try:
  6339. filename, _f = FCFileSaveDialog.get_saved_filename(
  6340. caption=_("Export SVG"),
  6341. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6342. filter=_filter)
  6343. except TypeError:
  6344. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6345. filename = str(filename)
  6346. if filename == "":
  6347. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6348. return
  6349. else:
  6350. self.export_svg(name, filename)
  6351. if self.defaults["global_open_style"] is False:
  6352. self.file_opened.emit("SVG", filename)
  6353. self.file_saved.emit("SVG", filename)
  6354. def on_file_exportpng(self):
  6355. self.defaults.report_usage("on_file_exportpng")
  6356. App.log.debug("on_file_exportpng()")
  6357. self.date = str(datetime.today()).rpartition('.')[0]
  6358. self.date = ''.join(c for c in self.date if c not in ':-')
  6359. self.date = self.date.replace(' ', '_')
  6360. if self.is_legacy is False:
  6361. image = _screenshot()
  6362. data = np.asarray(image)
  6363. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6364. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6365. return
  6366. filter_ = "PNG File (*.png);;All Files (*.*)"
  6367. try:
  6368. filename, _f = FCFileSaveDialog.get_saved_filename(
  6369. caption=_("Export PNG Image"),
  6370. directory=self.get_last_save_folder() + '/png_' + self.date,
  6371. filter=filter_)
  6372. except TypeError:
  6373. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6374. filename = str(filename)
  6375. if filename == "":
  6376. self.inform.emit(_("Cancelled."))
  6377. return
  6378. else:
  6379. if self.is_legacy is False:
  6380. write_png(filename, data)
  6381. else:
  6382. self.plotcanvas.figure.savefig(filename)
  6383. if self.defaults["global_open_style"] is False:
  6384. self.file_opened.emit("png", filename)
  6385. self.file_saved.emit("png", filename)
  6386. def on_file_savegerber(self):
  6387. """
  6388. Callback for menu item in Project context menu.
  6389. :return: None
  6390. """
  6391. self.defaults.report_usage("on_file_savegerber")
  6392. App.log.debug("on_file_savegerber()")
  6393. obj = self.collection.get_active()
  6394. if obj is None:
  6395. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6396. return
  6397. # Check for more compatible types and add as required
  6398. if not isinstance(obj, GerberObject):
  6399. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6400. return
  6401. name = self.collection.get_active().options["name"]
  6402. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6403. try:
  6404. filename, _f = FCFileSaveDialog.get_saved_filename(
  6405. caption="Save Gerber source file",
  6406. directory=self.get_last_save_folder() + '/' + name,
  6407. filter=_filter)
  6408. except TypeError:
  6409. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6410. filename = str(filename)
  6411. if filename == "":
  6412. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6413. return
  6414. else:
  6415. self.save_source_file(name, filename)
  6416. if self.defaults["global_open_style"] is False:
  6417. self.file_opened.emit("Gerber", filename)
  6418. self.file_saved.emit("Gerber", filename)
  6419. def on_file_savescript(self):
  6420. """
  6421. Callback for menu item in Project context menu.
  6422. :return: None
  6423. """
  6424. self.defaults.report_usage("on_file_savescript")
  6425. App.log.debug("on_file_savescript()")
  6426. obj = self.collection.get_active()
  6427. if obj is None:
  6428. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6429. return
  6430. # Check for more compatible types and add as required
  6431. if not isinstance(obj, ScriptObject):
  6432. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6433. return
  6434. name = self.collection.get_active().options["name"]
  6435. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6436. try:
  6437. filename, _f = FCFileSaveDialog.get_saved_filename(
  6438. caption="Save Script source file",
  6439. directory=self.get_last_save_folder() + '/' + name,
  6440. filter=_filter)
  6441. except TypeError:
  6442. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6443. filename = str(filename)
  6444. if filename == "":
  6445. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6446. return
  6447. else:
  6448. self.save_source_file(name, filename)
  6449. if self.defaults["global_open_style"] is False:
  6450. self.file_opened.emit("Script", filename)
  6451. self.file_saved.emit("Script", filename)
  6452. def on_file_savedocument(self):
  6453. """
  6454. Callback for menu item in Project context menu.
  6455. :return: None
  6456. """
  6457. self.defaults.report_usage("on_file_savedocument")
  6458. App.log.debug("on_file_savedocument()")
  6459. obj = self.collection.get_active()
  6460. if obj is None:
  6461. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6462. return
  6463. # Check for more compatible types and add as required
  6464. if not isinstance(obj, ScriptObject):
  6465. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6466. return
  6467. name = self.collection.get_active().options["name"]
  6468. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6469. try:
  6470. filename, _f = FCFileSaveDialog.get_saved_filename(
  6471. caption="Save Document source file",
  6472. directory=self.get_last_save_folder() + '/' + name,
  6473. filter=_filter)
  6474. except TypeError:
  6475. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6476. filename = str(filename)
  6477. if filename == "":
  6478. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6479. return
  6480. else:
  6481. self.save_source_file(name, filename)
  6482. if self.defaults["global_open_style"] is False:
  6483. self.file_opened.emit("Document", filename)
  6484. self.file_saved.emit("Document", filename)
  6485. def on_file_saveexcellon(self):
  6486. """
  6487. Callback for menu item in project context menu.
  6488. :return: None
  6489. """
  6490. self.defaults.report_usage("on_file_saveexcellon")
  6491. App.log.debug("on_file_saveexcellon()")
  6492. obj = self.collection.get_active()
  6493. if obj is None:
  6494. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6495. return
  6496. # Check for more compatible types and add as required
  6497. if not isinstance(obj, ExcellonObject):
  6498. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6499. return
  6500. name = self.collection.get_active().options["name"]
  6501. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6502. try:
  6503. filename, _f = FCFileSaveDialog.get_saved_filename(
  6504. caption=_("Save Excellon source file"),
  6505. directory=self.get_last_save_folder() + '/' + name,
  6506. filter=_filter)
  6507. except TypeError:
  6508. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6509. filename = str(filename)
  6510. if filename == "":
  6511. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6512. return
  6513. else:
  6514. self.save_source_file(name, filename)
  6515. if self.defaults["global_open_style"] is False:
  6516. self.file_opened.emit("Excellon", filename)
  6517. self.file_saved.emit("Excellon", filename)
  6518. def on_file_exportexcellon(self):
  6519. """
  6520. Callback for menu item File->Export->Excellon.
  6521. :return: None
  6522. """
  6523. self.defaults.report_usage("on_file_exportexcellon")
  6524. App.log.debug("on_file_exportexcellon()")
  6525. obj = self.collection.get_active()
  6526. if obj is None:
  6527. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6528. return
  6529. # Check for more compatible types and add as required
  6530. if not isinstance(obj, ExcellonObject):
  6531. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6532. return
  6533. name = self.collection.get_active().options["name"]
  6534. _filter = self.defaults["excellon_save_filters"]
  6535. try:
  6536. filename, _f = FCFileSaveDialog.get_saved_filename(
  6537. caption=_("Export Excellon"),
  6538. directory=self.get_last_save_folder() + '/' + name,
  6539. filter=_filter)
  6540. except TypeError:
  6541. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6542. filename = str(filename)
  6543. if filename == "":
  6544. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6545. return
  6546. else:
  6547. used_extension = filename.rpartition('.')[2]
  6548. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6549. self.export_excellon(name, filename)
  6550. if self.defaults["global_open_style"] is False:
  6551. self.file_opened.emit("Excellon", filename)
  6552. self.file_saved.emit("Excellon", filename)
  6553. def on_file_exportgerber(self):
  6554. """
  6555. Callback for menu item File->Export->Gerber.
  6556. :return: None
  6557. """
  6558. self.defaults.report_usage("on_file_exportgerber")
  6559. App.log.debug("on_file_exportgerber()")
  6560. obj = self.collection.get_active()
  6561. if obj is None:
  6562. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6563. return
  6564. # Check for more compatible types and add as required
  6565. if not isinstance(obj, GerberObject):
  6566. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6567. return
  6568. name = self.collection.get_active().options["name"]
  6569. _filter_ = self.defaults['gerber_save_filters']
  6570. try:
  6571. filename, _f = FCFileSaveDialog.get_saved_filename(
  6572. caption=_("Export Gerber"),
  6573. directory=self.get_last_save_folder() + '/' + name,
  6574. filter=_filter_)
  6575. except TypeError:
  6576. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6577. filename = str(filename)
  6578. if filename == "":
  6579. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6580. return
  6581. else:
  6582. used_extension = filename.rpartition('.')[2]
  6583. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6584. self.export_gerber(name, filename)
  6585. if self.defaults["global_open_style"] is False:
  6586. self.file_opened.emit("Gerber", filename)
  6587. self.file_saved.emit("Gerber", filename)
  6588. def on_file_exportdxf(self):
  6589. """
  6590. Callback for menu item File->Export DXF.
  6591. :return: None
  6592. """
  6593. self.defaults.report_usage("on_file_exportdxf")
  6594. App.log.debug("on_file_exportdxf()")
  6595. obj = self.collection.get_active()
  6596. if obj is None:
  6597. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6598. msg = _("Please Select a Geometry object to export")
  6599. msgbox = QtWidgets.QMessageBox()
  6600. msgbox.setInformativeText(msg)
  6601. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6602. msgbox.setDefaultButton(bt_ok)
  6603. msgbox.exec_()
  6604. return
  6605. # Check for more compatible types and add as required
  6606. if not isinstance(obj, GeometryObject):
  6607. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6608. msgbox = QtWidgets.QMessageBox()
  6609. msgbox.setInformativeText(msg)
  6610. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6611. msgbox.setDefaultButton(bt_ok)
  6612. msgbox.exec_()
  6613. return
  6614. name = self.collection.get_active().options["name"]
  6615. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6616. try:
  6617. filename, _f = FCFileSaveDialog.get_saved_filename(
  6618. caption=_("Export DXF"),
  6619. directory=self.get_last_save_folder() + '/' + name,
  6620. filter=_filter_)
  6621. except TypeError:
  6622. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6623. filename = str(filename)
  6624. if filename == "":
  6625. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6626. return
  6627. else:
  6628. self.export_dxf(name, filename)
  6629. if self.defaults["global_open_style"] is False:
  6630. self.file_opened.emit("DXF", filename)
  6631. self.file_saved.emit("DXF", filename)
  6632. def on_file_importsvg(self, type_of_obj):
  6633. """
  6634. Callback for menu item File->Import SVG.
  6635. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6636. :type type_of_obj: str
  6637. :return: None
  6638. """
  6639. self.defaults.report_usage("on_file_importsvg")
  6640. App.log.debug("on_file_importsvg()")
  6641. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6642. try:
  6643. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6644. directory=self.get_last_folder(), filter=_filter_)
  6645. except TypeError:
  6646. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6647. filter=_filter_)
  6648. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6649. type_of_obj = "geometry"
  6650. filenames = [str(filename) for filename in filenames]
  6651. if len(filenames) == 0:
  6652. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6653. else:
  6654. for filename in filenames:
  6655. if filename != '':
  6656. self.worker_task.emit({'fcn': self.import_svg,
  6657. 'params': [filename, type_of_obj]})
  6658. def on_file_importdxf(self, type_of_obj):
  6659. """
  6660. Callback for menu item File->Import DXF.
  6661. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6662. :type type_of_obj: str
  6663. :return: None
  6664. """
  6665. self.defaults.report_usage("on_file_importdxf")
  6666. App.log.debug("on_file_importdxf()")
  6667. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6668. try:
  6669. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6670. directory=self.get_last_folder(),
  6671. filter=_filter_)
  6672. except TypeError:
  6673. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6674. filter=_filter_)
  6675. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6676. type_of_obj = "geometry"
  6677. filenames = [str(filename) for filename in filenames]
  6678. if len(filenames) == 0:
  6679. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6680. else:
  6681. for filename in filenames:
  6682. if filename != '':
  6683. self.worker_task.emit({'fcn': self.import_dxf,
  6684. 'params': [filename, type_of_obj]})
  6685. # ###############################################################################################################
  6686. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6687. # ###############################################################################################################
  6688. def init_code_editor(self, name):
  6689. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6690. # add the tab if it was closed
  6691. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6692. self.text_editor_tab.setObjectName('text_editor_tab')
  6693. # delete the absolute and relative position and messages in the infobar
  6694. self.ui.position_label.setText("")
  6695. # self.ui.rel_position_label.setText("")
  6696. # first clear previous text in text editor (if any)
  6697. self.text_editor_tab.code_editor.clear()
  6698. self.text_editor_tab.code_editor.setReadOnly(False)
  6699. self.toggle_codeeditor = True
  6700. self.text_editor_tab.code_editor.completer_enable = False
  6701. self.text_editor_tab.buttonRun.hide()
  6702. # make sure to keep a reference to the code editor
  6703. self.reference_code_editor = self.text_editor_tab.code_editor
  6704. # Switch plot_area to CNCJob tab
  6705. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6706. def on_view_source(self):
  6707. """
  6708. Called when the user wants to see the source file of the selected object
  6709. :return:
  6710. """
  6711. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6712. self.proc_container.view.set_busy(_("Loading..."))
  6713. try:
  6714. obj = self.collection.get_active()
  6715. except Exception as e:
  6716. log.debug("App.on_view_source() --> %s" % str(e))
  6717. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6718. return 'fail'
  6719. if obj is None:
  6720. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6721. return 'fail'
  6722. flt = "All Files (*.*)"
  6723. if obj.kind == 'gerber':
  6724. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6725. elif obj.kind == 'excellon':
  6726. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6727. elif obj.kind == 'cncjob':
  6728. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6729. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6730. # add the tab if it was closed
  6731. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6732. self.source_editor_tab.setObjectName('source_editor_tab')
  6733. # delete the absolute and relative position and messages in the infobar
  6734. self.ui.position_label.setText("")
  6735. # self.ui.rel_position_label.setText("")
  6736. # first clear previous text in text editor (if any)
  6737. self.source_editor_tab.code_editor.clear()
  6738. self.source_editor_tab.code_editor.setReadOnly(False)
  6739. self.source_editor_tab.code_editor.completer_enable = False
  6740. self.source_editor_tab.buttonRun.hide()
  6741. # Switch plot_area to CNCJob tab
  6742. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6743. try:
  6744. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6745. except TypeError:
  6746. pass
  6747. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6748. try:
  6749. self.source_editor_tab.buttonSave.clicked.disconnect()
  6750. except TypeError:
  6751. pass
  6752. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6753. # then append the text from GCode to the text editor
  6754. if obj.kind == 'cncjob':
  6755. try:
  6756. file = obj.export_gcode(
  6757. preamble=self.defaults["cncjob_prepend"],
  6758. postamble=self.defaults["cncjob_append"],
  6759. to_file=True)
  6760. if file == 'fail':
  6761. return 'fail'
  6762. except AttributeError:
  6763. self.inform.emit('[WARNING_NOTCL] %s' %
  6764. _("There is no selected object for which to see it's source file code."))
  6765. return 'fail'
  6766. else:
  6767. try:
  6768. file = StringIO(obj.source_file)
  6769. except (AttributeError, TypeError):
  6770. self.inform.emit('[WARNING_NOTCL] %s' %
  6771. _("There is no selected object for which to see it's source file code."))
  6772. return 'fail'
  6773. self.source_editor_tab.t_frame.hide()
  6774. try:
  6775. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6776. # for line in file:
  6777. # QtWidgets.QApplication.processEvents()
  6778. # proc_line = str(line).strip('\n')
  6779. # self.source_editor_tab.code_editor.append(proc_line)
  6780. except Exception as e:
  6781. log.debug('App.on_view_source() -->%s' % str(e))
  6782. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6783. return
  6784. self.source_editor_tab.handleTextChanged()
  6785. self.source_editor_tab.t_frame.show()
  6786. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6787. self.proc_container.view.set_idle()
  6788. # self.ui.show()
  6789. def on_toggle_code_editor(self):
  6790. self.defaults.report_usage("on_toggle_code_editor()")
  6791. if self.toggle_codeeditor is False:
  6792. self.init_code_editor(name=_("Code Editor"))
  6793. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6794. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6795. self.text_editor_tab.buttonSave.clicked.disconnect()
  6796. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6797. else:
  6798. for idx in range(self.ui.plot_tab_area.count()):
  6799. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6800. self.ui.plot_tab_area.closeTab(idx)
  6801. break
  6802. self.toggle_codeeditor = False
  6803. def on_code_editor_close(self):
  6804. self.toggle_codeeditor = False
  6805. def goto_text_line(self):
  6806. """
  6807. Will scroll a text to the specified text line.
  6808. :return: None
  6809. """
  6810. dia_box = Dialog_box(title=_("Go to Line ..."),
  6811. label=_("Line:"),
  6812. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6813. initial_text='')
  6814. try:
  6815. line = int(dia_box.location) - 1
  6816. except (ValueError, TypeError):
  6817. line = 0
  6818. if dia_box.ok:
  6819. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6820. # at the top of the window
  6821. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6822. # get the document() of the TextEditor
  6823. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6824. # create a Text Cursor based on the searched line
  6825. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6826. # set cursor of the code editor with the cursor at the searcehd line
  6827. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6828. def on_filenewscript(self, silent=False):
  6829. """
  6830. Will create a new script file and open it in the Code Editor
  6831. :param silent: if True will not display status messages
  6832. :param name: if specified will be the name of the new script
  6833. :param text: pass a source file to the newly created script to be loaded in it
  6834. :return: None
  6835. """
  6836. if silent is False:
  6837. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6838. # delete the absolute and relative position and messages in the infobar
  6839. self.ui.position_label.setText("")
  6840. # self.ui.rel_position_label.setText("")
  6841. self.new_script_object()
  6842. # script_text = script_obj.source_file
  6843. #
  6844. # self.proc_container.view.set_busy(_("Loading..."))
  6845. # script_obj.script_editor_tab.t_frame.hide()
  6846. #
  6847. # script_obj.script_editor_tab.t_frame.show()
  6848. # self.proc_container.view.set_idle()
  6849. def on_fileopenscript(self, name=None, silent=False):
  6850. """
  6851. Will open a Tcl script file into the Code Editor
  6852. :param silent: if True will not display status messages
  6853. :param name: name of a Tcl script file to open
  6854. :return: None
  6855. """
  6856. self.defaults.report_usage("on_fileopenscript")
  6857. App.log.debug("on_fileopenscript()")
  6858. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6859. "All Files (*.*)"
  6860. if name:
  6861. filenames = [name]
  6862. else:
  6863. try:
  6864. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6865. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6866. except TypeError:
  6867. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6868. if len(filenames) == 0:
  6869. if silent is False:
  6870. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6871. else:
  6872. for filename in filenames:
  6873. if filename != '':
  6874. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6875. def on_fileopenscript_example(self, name=None, silent=False):
  6876. """
  6877. Will open a Tcl script file into the Code Editor
  6878. :param silent: if True will not display status messages
  6879. :param name: name of a Tcl script file to open
  6880. :return:
  6881. """
  6882. self.defaults.report_usage("on_fileopenscript_example")
  6883. log.debug("on_fileopenscript_example()")
  6884. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6885. "All Files (*.*)"
  6886. # test if the app was frozen and choose the path for the configuration file
  6887. if getattr(sys, "frozen", False) is True:
  6888. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6889. else:
  6890. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6891. if name:
  6892. filenames = [name]
  6893. else:
  6894. try:
  6895. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6896. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6897. except TypeError:
  6898. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6899. if len(filenames) == 0:
  6900. if silent is False:
  6901. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6902. else:
  6903. for filename in filenames:
  6904. if filename != '':
  6905. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6906. def on_filerunscript(self, name=None, silent=False):
  6907. """
  6908. File menu callback for loading and running a TCL script.
  6909. :param silent: if True will not display status messages
  6910. :param name: name of a Tcl script file to be run by FlatCAM
  6911. :return: None
  6912. """
  6913. self.defaults.report_usage("on_filerunscript")
  6914. App.log.debug("on_file_runscript()")
  6915. if name:
  6916. filename = name
  6917. if self.cmd_line_headless != 1:
  6918. self.splash.showMessage('%s: %ssec\n%s' %
  6919. (_("Canvas initialization started.\n"
  6920. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6921. _("Executing ScriptObject file.")
  6922. ),
  6923. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6924. color=QtGui.QColor("gray"))
  6925. else:
  6926. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6927. "All Files (*.*)"
  6928. try:
  6929. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6930. directory=self.get_last_folder(), filter=_filter_)
  6931. except TypeError:
  6932. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6933. # The Qt methods above will return a QString which can cause problems later.
  6934. # So far json.dump() will fail to serialize it.
  6935. filename = str(filename)
  6936. if filename == "":
  6937. if silent is False:
  6938. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6939. else:
  6940. if self.cmd_line_headless != 1:
  6941. if self.ui.shell_dock.isHidden():
  6942. self.ui.shell_dock.show()
  6943. try:
  6944. with open(filename, "r") as tcl_script:
  6945. cmd_line_shellfile_content = tcl_script.read()
  6946. if self.cmd_line_headless != 1:
  6947. self.shell.exec_command(cmd_line_shellfile_content)
  6948. else:
  6949. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6950. if silent is False:
  6951. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6952. except Exception as e:
  6953. log.debug("App.on_filerunscript() -> %s" % str(e))
  6954. sys.exit(2)
  6955. def on_file_saveproject(self, silent=False):
  6956. """
  6957. Callback for menu item File->Save Project. Saves the project to
  6958. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6959. if set to None. The project is saved by calling ``self.save_project()``.
  6960. :param silent: if True will not display status messages
  6961. :return: None
  6962. """
  6963. self.defaults.report_usage("on_file_saveproject")
  6964. if self.project_filename is None:
  6965. self.on_file_saveprojectas()
  6966. else:
  6967. self.worker_task.emit({'fcn': self.save_project,
  6968. 'params': [self.project_filename, silent]})
  6969. if self.defaults["global_open_style"] is False:
  6970. self.file_opened.emit("project", self.project_filename)
  6971. self.file_saved.emit("project", self.project_filename)
  6972. self.set_ui_title(name=self.project_filename)
  6973. self.should_we_save = False
  6974. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6975. """
  6976. Callback for menu item File->Save Project As... Opens a file
  6977. chooser and saves the project to the given file via
  6978. ``self.save_project()``.
  6979. :param make_copy if to be create a copy of the project; boolean
  6980. :param use_thread: if to be run in a separate thread; boolean
  6981. :param quit_action: if to be followed by quiting the application; boolean
  6982. :return: None
  6983. """
  6984. self.defaults.report_usage("on_file_saveprojectas")
  6985. self.date = str(datetime.today()).rpartition('.')[0]
  6986. self.date = ''.join(c for c in self.date if c not in ':-')
  6987. self.date = self.date.replace(' ', '_')
  6988. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6989. try:
  6990. filename, _f = FCFileSaveDialog.get_saved_filename(
  6991. caption=_("Save Project As ..."),
  6992. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6993. proj=_("Project")),
  6994. filter=filter_
  6995. )
  6996. except TypeError:
  6997. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6998. filename = str(filename)
  6999. if filename == '':
  7000. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7001. return
  7002. if use_thread is True:
  7003. self.worker_task.emit({'fcn': self.save_project,
  7004. 'params': [filename, quit_action]})
  7005. else:
  7006. self.save_project(filename, quit_action)
  7007. # self.save_project(filename)
  7008. if self.defaults["global_open_style"] is False:
  7009. self.file_opened.emit("project", filename)
  7010. self.file_saved.emit("project", filename)
  7011. if not make_copy:
  7012. self.project_filename = filename
  7013. self.set_ui_title(name=self.project_filename)
  7014. self.should_we_save = False
  7015. def on_file_save_objects_pdf(self, use_thread=True):
  7016. self.date = str(datetime.today()).rpartition('.')[0]
  7017. self.date = ''.join(c for c in self.date if c not in ':-')
  7018. self.date = self.date.replace(' ', '_')
  7019. try:
  7020. obj_selection = self.collection.get_selected()
  7021. if len(obj_selection) == 1:
  7022. obj_name = str(obj_selection[0].options['name'])
  7023. else:
  7024. obj_name = _("FlatCAM objects print")
  7025. except AttributeError as err:
  7026. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7027. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7028. return
  7029. if not obj_selection:
  7030. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7031. return
  7032. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7033. try:
  7034. filename, _f = FCFileSaveDialog.get_saved_filename(
  7035. caption=_("Save Object as PDF ..."),
  7036. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7037. obj_name=obj_name,
  7038. date=self.date),
  7039. filter=filter_
  7040. )
  7041. except TypeError:
  7042. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7043. filename = str(filename)
  7044. if filename == '':
  7045. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7046. return
  7047. if use_thread is True:
  7048. self.proc_container.new(_("Printing PDF ... Please wait."))
  7049. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7050. else:
  7051. self.save_pdf(filename, obj_selection)
  7052. # self.save_project(filename)
  7053. if self.defaults["global_open_style"] is False:
  7054. self.file_opened.emit("pdf", filename)
  7055. self.file_saved.emit("pdf", filename)
  7056. def save_pdf(self, file_name, obj_selection):
  7057. p_size = self.defaults['global_workspaceT']
  7058. orientation = self.defaults['global_workspace_orientation']
  7059. color = 'black'
  7060. transparency_level = 1.0
  7061. self.pagesize = {}
  7062. self.pagesize.update(
  7063. {
  7064. 'Bounds': None,
  7065. 'A0': (841 * mm, 1189 * mm),
  7066. 'A1': (594 * mm, 841 * mm),
  7067. 'A2': (420 * mm, 594 * mm),
  7068. 'A3': (297 * mm, 420 * mm),
  7069. 'A4': (210 * mm, 297 * mm),
  7070. 'A5': (148 * mm, 210 * mm),
  7071. 'A6': (105 * mm, 148 * mm),
  7072. 'A7': (74 * mm, 105 * mm),
  7073. 'A8': (52 * mm, 74 * mm),
  7074. 'A9': (37 * mm, 52 * mm),
  7075. 'A10': (26 * mm, 37 * mm),
  7076. 'B0': (1000 * mm, 1414 * mm),
  7077. 'B1': (707 * mm, 1000 * mm),
  7078. 'B2': (500 * mm, 707 * mm),
  7079. 'B3': (353 * mm, 500 * mm),
  7080. 'B4': (250 * mm, 353 * mm),
  7081. 'B5': (176 * mm, 250 * mm),
  7082. 'B6': (125 * mm, 176 * mm),
  7083. 'B7': (88 * mm, 125 * mm),
  7084. 'B8': (62 * mm, 88 * mm),
  7085. 'B9': (44 * mm, 62 * mm),
  7086. 'B10': (31 * mm, 44 * mm),
  7087. 'C0': (917 * mm, 1297 * mm),
  7088. 'C1': (648 * mm, 917 * mm),
  7089. 'C2': (458 * mm, 648 * mm),
  7090. 'C3': (324 * mm, 458 * mm),
  7091. 'C4': (229 * mm, 324 * mm),
  7092. 'C5': (162 * mm, 229 * mm),
  7093. 'C6': (114 * mm, 162 * mm),
  7094. 'C7': (81 * mm, 114 * mm),
  7095. 'C8': (57 * mm, 81 * mm),
  7096. 'C9': (40 * mm, 57 * mm),
  7097. 'C10': (28 * mm, 40 * mm),
  7098. # American paper sizes
  7099. 'LETTER': (8.5 * inch, 11 * inch),
  7100. 'LEGAL': (8.5 * inch, 14 * inch),
  7101. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7102. # From https://en.wikipedia.org/wiki/Paper_size
  7103. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7104. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7105. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7106. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7107. 'LEDGER': (17 * inch, 11 * inch),
  7108. }
  7109. )
  7110. exported_svg = []
  7111. for obj in obj_selection:
  7112. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7113. scale_factor_x=None, scale_factor_y=None,
  7114. skew_factor_x=None, skew_factor_y=None,
  7115. mirror=None)
  7116. if obj.kind.lower() == 'gerber':
  7117. # color = self.defaults["gerber_plot_fill"][:-2]
  7118. color = obj.fill_color[:-2]
  7119. elif obj.kind.lower() == 'excellon':
  7120. color = '#C40000'
  7121. elif obj.kind.lower() == 'geometry':
  7122. color = self.defaults["global_draw_color"]
  7123. # Change the attributes of the exported SVG
  7124. # We don't need stroke-width
  7125. # We set opacity to maximum
  7126. # We set the colour to WHITE
  7127. root = ET.fromstring(svg_obj)
  7128. for child in root:
  7129. child.set('fill', str(color))
  7130. child.set('opacity', str(transparency_level))
  7131. child.set('stroke', str(color))
  7132. exported_svg.append(ET.tostring(root))
  7133. xmin = Inf
  7134. ymin = Inf
  7135. xmax = -Inf
  7136. ymax = -Inf
  7137. for obj in obj_selection:
  7138. try:
  7139. gxmin, gymin, gxmax, gymax = obj.bounds()
  7140. xmin = min([xmin, gxmin])
  7141. ymin = min([ymin, gymin])
  7142. xmax = max([xmax, gxmax])
  7143. ymax = max([ymax, gymax])
  7144. except Exception as e:
  7145. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7146. # Determine bounding area for svg export
  7147. bounds = [xmin, ymin, xmax, ymax]
  7148. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7149. # This contain the measure units
  7150. uom = obj_selection[0].units.lower()
  7151. # Define a boundary around SVG of about 1.0mm (~39mils)
  7152. if uom in "mm":
  7153. boundary = 1.0
  7154. else:
  7155. boundary = 0.0393701
  7156. # Convert everything to strings for use in the xml doc
  7157. svgwidth = str(size[0] + (2 * boundary))
  7158. svgheight = str(size[1] + (2 * boundary))
  7159. minx = str(bounds[0] - boundary)
  7160. miny = str(bounds[1] + boundary + size[1])
  7161. # Add a SVG Header and footer to the svg output from shapely
  7162. # The transform flips the Y Axis so that everything renders
  7163. # properly within svg apps such as inkscape
  7164. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7165. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7166. svg_header += 'width="' + svgwidth + uom + '" '
  7167. svg_header += 'height="' + svgheight + uom + '" '
  7168. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7169. svg_header += '>'
  7170. svg_header += '<g transform="scale(1,-1)">'
  7171. svg_footer = '</g> </svg>'
  7172. svg_elem = str(svg_header)
  7173. for svg_item in exported_svg:
  7174. svg_elem += str(svg_item)
  7175. svg_elem += str(svg_footer)
  7176. # Parse the xml through a xml parser just to add line feeds
  7177. # and to make it look more pretty for the output
  7178. doc = parse_xml_string(svg_elem)
  7179. doc_final = doc.toprettyxml()
  7180. try:
  7181. if self.defaults['units'].upper() == 'IN':
  7182. unit = inch
  7183. else:
  7184. unit = mm
  7185. doc_final = StringIO(doc_final)
  7186. drawing = svg2rlg(doc_final)
  7187. if p_size == 'Bounds':
  7188. renderPDF.drawToFile(drawing, file_name)
  7189. else:
  7190. if orientation == 'p':
  7191. page_size = portrait(self.pagesize[p_size])
  7192. else:
  7193. page_size = landscape(self.pagesize[p_size])
  7194. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7195. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7196. renderPDF.draw(drawing, my_canvas, 0, 0)
  7197. my_canvas.save()
  7198. except Exception as e:
  7199. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7200. return 'fail'
  7201. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7202. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7203. """
  7204. Exports a Geometry Object to an SVG file.
  7205. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7206. :param filename: Path to the SVG file to save to.
  7207. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7208. :return:
  7209. """
  7210. self.defaults.report_usage("export_svg()")
  7211. if filename is None:
  7212. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7213. is not None else self.defaults["global_last_folder"]
  7214. self.log.debug("export_svg()")
  7215. try:
  7216. obj = self.collection.get_by_name(str(obj_name))
  7217. except Exception:
  7218. # TODO: The return behavior has not been established... should raise exception?
  7219. return "Could not retrieve object: %s" % obj_name
  7220. with self.proc_container.new(_("Exporting SVG")) as proc:
  7221. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7222. # Determine bounding area for svg export
  7223. bounds = obj.bounds()
  7224. size = obj.size()
  7225. # Convert everything to strings for use in the xml doc
  7226. svgwidth = str(size[0])
  7227. svgheight = str(size[1])
  7228. minx = str(bounds[0])
  7229. miny = str(bounds[1] - size[1])
  7230. uom = obj.units.lower()
  7231. # Add a SVG Header and footer to the svg output from shapely
  7232. # The transform flips the Y Axis so that everything renders
  7233. # properly within svg apps such as inkscape
  7234. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7235. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7236. svg_header += 'width="' + svgwidth + uom + '" '
  7237. svg_header += 'height="' + svgheight + uom + '" '
  7238. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7239. svg_header += '<g transform="scale(1,-1)">'
  7240. svg_footer = '</g> </svg>'
  7241. svg_elem = svg_header + exported_svg + svg_footer
  7242. # Parse the xml through a xml parser just to add line feeds
  7243. # and to make it look more pretty for the output
  7244. svgcode = parse_xml_string(svg_elem)
  7245. svgcode = svgcode.toprettyxml()
  7246. try:
  7247. with open(filename, 'w') as fp:
  7248. fp.write(svgcode)
  7249. except PermissionError:
  7250. self.inform.emit('[WARNING] %s' %
  7251. _("Permission denied, saving not possible.\n"
  7252. "Most likely another app is holding the file open and not accessible."))
  7253. return 'fail'
  7254. if self.defaults["global_open_style"] is False:
  7255. self.file_opened.emit("SVG", filename)
  7256. self.file_saved.emit("SVG", filename)
  7257. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7258. def save_source_file(self, obj_name, filename, use_thread=True):
  7259. """
  7260. Exports a FlatCAM Object to an Gerber/Excellon file.
  7261. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7262. :param filename: Path to the Gerber file to save to.
  7263. :param use_thread: if to be run in a separate thread
  7264. :return:
  7265. """
  7266. self.defaults.report_usage("save source file()")
  7267. if filename is None:
  7268. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7269. is not None else self.defaults["global_last_folder"]
  7270. self.log.debug("save source file()")
  7271. obj = self.collection.get_by_name(obj_name)
  7272. file_string = StringIO(obj.source_file)
  7273. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7274. if file_string.getvalue() == '':
  7275. self.inform.emit('[ERROR_NOTCL] %s' %
  7276. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7277. return 'fail'
  7278. try:
  7279. with open(filename, 'w') as file:
  7280. file.writelines('G04*\n')
  7281. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7282. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7283. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7284. file.writelines('G04 Created on : %s*\n' % time_string)
  7285. for line in file_string:
  7286. file.writelines(line)
  7287. except PermissionError:
  7288. self.inform.emit('[WARNING] %s' %
  7289. _("Permission denied, saving not possible.\n"
  7290. "Most likely another app is holding the file open and not accessible."))
  7291. return 'fail'
  7292. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7293. """
  7294. Exports a Excellon Object to an Excellon file.
  7295. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7296. :param filename: Path to the Excellon file to save to.
  7297. :param local_use:
  7298. :param use_thread: if to be run in a separate thread
  7299. :return:
  7300. """
  7301. self.defaults.report_usage("export_excellon()")
  7302. if filename is None:
  7303. if self.defaults["global_last_save_folder"]:
  7304. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7305. else:
  7306. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7307. self.log.debug("export_excellon()")
  7308. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7309. self.defaults["excellon_exp_decimals"]
  7310. )
  7311. if local_use is None:
  7312. try:
  7313. obj = self.collection.get_by_name(str(obj_name))
  7314. except Exception:
  7315. return "Could not retrieve object: %s" % obj_name
  7316. else:
  7317. obj = local_use
  7318. if not isinstance(obj, ExcellonObject):
  7319. self.inform.emit('[ERROR_NOTCL] %s' %
  7320. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7321. return
  7322. # updated units
  7323. eunits = self.defaults["excellon_exp_units"]
  7324. ewhole = self.defaults["excellon_exp_integer"]
  7325. efract = self.defaults["excellon_exp_decimals"]
  7326. ezeros = self.defaults["excellon_exp_zeros"]
  7327. eformat = self.defaults["excellon_exp_format"]
  7328. slot_type = self.defaults["excellon_exp_slot_type"]
  7329. fc_units = self.defaults['units'].upper()
  7330. if fc_units == 'MM':
  7331. factor = 1 if eunits == 'METRIC' else 0.03937
  7332. else:
  7333. factor = 25.4 if eunits == 'METRIC' else 1
  7334. def make_excellon():
  7335. try:
  7336. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7337. header = 'M48\n'
  7338. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7339. (str(self.version), str(self.version_date))
  7340. header += ';Filename: %s' % str(obj_name) + '\n'
  7341. header += ';Created on : %s' % time_str + '\n'
  7342. if eformat == 'dec':
  7343. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7344. header += eunits + '\n'
  7345. for tool in obj.tools:
  7346. if eunits == 'METRIC':
  7347. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7348. tool=str(tool),
  7349. dec=2)
  7350. else:
  7351. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7352. tool=str(tool),
  7353. dec=4)
  7354. else:
  7355. if ezeros == 'LZ':
  7356. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7357. form='ndec', e_zeros='LZ', factor=factor,
  7358. slot_type=slot_type)
  7359. header += '%s,%s\n' % (eunits, 'LZ')
  7360. header += format_exc
  7361. for tool in obj.tools:
  7362. if eunits == 'METRIC':
  7363. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7364. tool=str(tool),
  7365. dec=2)
  7366. else:
  7367. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7368. tool=str(tool),
  7369. dec=4)
  7370. else:
  7371. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7372. form='ndec', e_zeros='TZ', factor=factor,
  7373. slot_type=slot_type)
  7374. header += '%s,%s\n' % (eunits, 'TZ')
  7375. header += format_exc
  7376. for tool in obj.tools:
  7377. if eunits == 'METRIC':
  7378. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7379. tool=str(tool),
  7380. dec=2)
  7381. else:
  7382. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7383. tool=str(tool),
  7384. dec=4)
  7385. header += '%\n'
  7386. footer = 'M30\n'
  7387. exported_excellon = header
  7388. exported_excellon += excellon_code
  7389. exported_excellon += footer
  7390. if local_use is None:
  7391. try:
  7392. with open(filename, 'w') as fp:
  7393. fp.write(exported_excellon)
  7394. except PermissionError:
  7395. self.inform.emit('[WARNING] %s' %
  7396. _("Permission denied, saving not possible.\n"
  7397. "Most likely another app is holding the file open and not accessible."))
  7398. return 'fail'
  7399. if self.defaults["global_open_style"] is False:
  7400. self.file_opened.emit("Excellon", filename)
  7401. self.file_saved.emit("Excellon", filename)
  7402. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7403. else:
  7404. return exported_excellon
  7405. except Exception as e:
  7406. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7407. return 'fail'
  7408. if use_thread is True:
  7409. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7410. def job_thread_exc(app_obj):
  7411. ret = make_excellon()
  7412. if ret == 'fail':
  7413. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7414. return
  7415. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7416. else:
  7417. eret = make_excellon()
  7418. if eret == 'fail':
  7419. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7420. return 'fail'
  7421. if local_use is not None:
  7422. return eret
  7423. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7424. """
  7425. Exports a Gerber Object to an Gerber file.
  7426. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7427. :param filename: Path to the Gerber file to save to.
  7428. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7429. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7430. :param use_thread: if to be run in a separate thread
  7431. :return:
  7432. """
  7433. self.defaults.report_usage("export_gerber()")
  7434. if filename is None:
  7435. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7436. is not None else self.defaults["global_last_folder"]
  7437. self.log.debug("export_gerber()")
  7438. if local_use is None:
  7439. try:
  7440. obj = self.collection.get_by_name(str(obj_name))
  7441. except Exception:
  7442. return "Could not retrieve object: %s" % obj_name
  7443. else:
  7444. obj = local_use
  7445. # updated units
  7446. gunits = self.defaults["gerber_exp_units"]
  7447. gwhole = self.defaults["gerber_exp_integer"]
  7448. gfract = self.defaults["gerber_exp_decimals"]
  7449. gzeros = self.defaults["gerber_exp_zeros"]
  7450. fc_units = self.defaults['units'].upper()
  7451. if fc_units == 'MM':
  7452. factor = 1 if gunits == 'MM' else 0.03937
  7453. else:
  7454. factor = 25.4 if gunits == 'MM' else 1
  7455. def make_gerber():
  7456. try:
  7457. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7458. header = 'G04*\n'
  7459. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7460. (str(self.version), str(self.version_date))
  7461. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7462. header += 'G04 Created on : %s*' % time_str + '\n'
  7463. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7464. header += "%MO{units}*%\n".format(units=gunits)
  7465. for apid in obj.apertures:
  7466. if obj.apertures[apid]['type'] == 'C':
  7467. header += "%ADD{apid}{type},{size}*%\n".format(
  7468. apid=str(apid),
  7469. type='C',
  7470. size=(factor * obj.apertures[apid]['size'])
  7471. )
  7472. elif obj.apertures[apid]['type'] == 'R':
  7473. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7474. apid=str(apid),
  7475. type='R',
  7476. width=(factor * obj.apertures[apid]['width']),
  7477. height=(factor * obj.apertures[apid]['height'])
  7478. )
  7479. elif obj.apertures[apid]['type'] == 'O':
  7480. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7481. apid=str(apid),
  7482. type='O',
  7483. width=(factor * obj.apertures[apid]['width']),
  7484. height=(factor * obj.apertures[apid]['height'])
  7485. )
  7486. header += '\n'
  7487. # obsolete units but some software may need it
  7488. if gunits == 'IN':
  7489. header += 'G70*\n'
  7490. else:
  7491. header += 'G71*\n'
  7492. # Absolute Mode
  7493. header += 'G90*\n'
  7494. header += 'G01*\n'
  7495. # positive polarity
  7496. header += '%LPD*%\n'
  7497. footer = 'M02*\n'
  7498. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7499. exported_gerber = header
  7500. exported_gerber += gerber_code
  7501. exported_gerber += footer
  7502. if local_use is None:
  7503. try:
  7504. with open(filename, 'w') as fp:
  7505. fp.write(exported_gerber)
  7506. except PermissionError:
  7507. self.inform.emit('[WARNING] %s' %
  7508. _("Permission denied, saving not possible.\n"
  7509. "Most likely another app is holding the file open and not accessible."))
  7510. return 'fail'
  7511. if self.defaults["global_open_style"] is False:
  7512. self.file_opened.emit("Gerber", filename)
  7513. self.file_saved.emit("Gerber", filename)
  7514. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7515. else:
  7516. return exported_gerber
  7517. except Exception as e:
  7518. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7519. return 'fail'
  7520. if use_thread is True:
  7521. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7522. def job_thread_grb(app_obj):
  7523. ret = make_gerber()
  7524. if ret == 'fail':
  7525. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7526. return
  7527. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7528. else:
  7529. gret = make_gerber()
  7530. if gret == 'fail':
  7531. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7532. return 'fail'
  7533. if local_use is not None:
  7534. return gret
  7535. def export_dxf(self, obj_name, filename, use_thread=True):
  7536. """
  7537. Exports a Geometry Object to an DXF file.
  7538. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7539. :param filename: Path to the DXF file to save to.
  7540. :param use_thread: if to be run in a separate thread
  7541. :return:
  7542. """
  7543. self.defaults.report_usage("export_dxf()")
  7544. if filename is None:
  7545. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7546. is not None else self.defaults["global_last_folder"]
  7547. self.log.debug("export_dxf()")
  7548. try:
  7549. obj = self.collection.get_by_name(str(obj_name))
  7550. except Exception:
  7551. # TODO: The return behavior has not been established... should raise exception?
  7552. return "Could not retrieve object: %s" % obj_name
  7553. def make_dxf():
  7554. try:
  7555. dxf_code = obj.export_dxf()
  7556. dxf_code.saveas(filename)
  7557. if self.defaults["global_open_style"] is False:
  7558. self.file_opened.emit("DXF", filename)
  7559. self.file_saved.emit("DXF", filename)
  7560. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7561. except Exception:
  7562. return 'fail'
  7563. if use_thread is True:
  7564. with self.proc_container.new(_("Exporting DXF")) as proc:
  7565. def job_thread_exc(app_obj):
  7566. ret_dxf_val = make_dxf()
  7567. if ret_dxf_val == 'fail':
  7568. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7569. return
  7570. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7571. else:
  7572. ret = make_dxf()
  7573. if ret == 'fail':
  7574. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7575. return
  7576. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7577. """
  7578. Adds a new Geometry Object to the projects and populates
  7579. it with shapes extracted from the SVG file.
  7580. :param plot: If True then the resulting object will be plotted on canvas
  7581. :param filename: Path to the SVG file.
  7582. :param geo_type: Type of FlatCAM object that will be created from SVG
  7583. :param outname: The name given to the resulting FlatCAM object
  7584. :return:
  7585. """
  7586. self.defaults.report_usage("import_svg()")
  7587. log.debug("App.import_svg()")
  7588. obj_type = ""
  7589. if geo_type is None or geo_type == "geometry":
  7590. obj_type = "geometry"
  7591. elif geo_type == "gerber":
  7592. obj_type = "gerber"
  7593. else:
  7594. self.inform.emit('[ERROR_NOTCL] %s' %
  7595. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7596. return
  7597. units = self.defaults['units'].upper()
  7598. def obj_init(geo_obj, app_obj):
  7599. geo_obj.import_svg(filename, obj_type, units=units)
  7600. geo_obj.multigeo = False
  7601. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7602. with self.proc_container.new(_("Importing SVG")) as proc:
  7603. # Object name
  7604. name = outname or filename.split('/')[-1].split('\\')[-1]
  7605. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7606. if ret == 'fail':
  7607. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7608. return 'fail'
  7609. # Register recent file
  7610. self.file_opened.emit("svg", filename)
  7611. # GUI feedback
  7612. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7613. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7614. """
  7615. Adds a new Geometry Object to the projects and populates
  7616. it with shapes extracted from the DXF file.
  7617. :param filename: Path to the DXF file.
  7618. :param geo_type: Type of FlatCAM object that will be created from DXF
  7619. :param outname: Name for the imported Geometry
  7620. :param plot: If True then the resulting object will be plotted on canvas
  7621. :return:
  7622. """
  7623. self.defaults.report_usage("import_dxf()")
  7624. obj_type = ""
  7625. if geo_type is None or geo_type == "geometry":
  7626. obj_type = "geometry"
  7627. elif geo_type == "gerber":
  7628. obj_type = geo_type
  7629. else:
  7630. self.inform.emit('[ERROR_NOTCL] %s' %
  7631. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7632. return
  7633. units = self.defaults['units'].upper()
  7634. def obj_init(geo_obj, app_obj):
  7635. geo_obj.import_dxf(filename, obj_type, units=units)
  7636. geo_obj.multigeo = False
  7637. with self.proc_container.new(_("Importing DXF")):
  7638. # Object name
  7639. name = outname or filename.split('/')[-1].split('\\')[-1]
  7640. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7641. if ret == 'fail':
  7642. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7643. return 'fail'
  7644. # Register recent file
  7645. self.file_opened.emit("dxf", filename)
  7646. # GUI feedback
  7647. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7648. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7649. """
  7650. Opens a Gerber file, parses it and creates a new object for
  7651. it in the program. Thread-safe.
  7652. :param outname: Name of the resulting object. None causes the
  7653. name to be that of the file. Str.
  7654. :param filename: Gerber file filename
  7655. :type filename: str
  7656. :param plot: boolean, to plot or not the resulting object
  7657. :param from_tcl: True if run from Tcl Shell
  7658. :return: None
  7659. """
  7660. # How the object should be initialized
  7661. def obj_init(gerber_obj, app_obj):
  7662. assert isinstance(gerber_obj, GerberObject), \
  7663. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7664. # Opening the file happens here
  7665. try:
  7666. gerber_obj.parse_file(filename)
  7667. except IOError:
  7668. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7669. return "fail"
  7670. except ParseError as err:
  7671. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7672. app_obj.log.error(str(err))
  7673. return "fail"
  7674. except Exception as e:
  7675. log.debug("App.open_gerber() --> %s" % str(e))
  7676. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7677. msg += traceback.format_exc()
  7678. app_obj.inform.emit(msg)
  7679. return "fail"
  7680. if gerber_obj.is_empty():
  7681. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7682. _("Object is not Gerber file or empty. Aborting object creation."))
  7683. return "fail"
  7684. App.log.debug("open_gerber()")
  7685. with self.proc_container.new(_("Opening Gerber")):
  7686. # Object name
  7687. name = outname or filename.split('/')[-1].split('\\')[-1]
  7688. # # ## Object creation # ##
  7689. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7690. if ret_val == 'fail':
  7691. if from_tcl:
  7692. filename = self.defaults['global_tcl_path'] + '/' + name
  7693. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7694. if ret_val == 'fail':
  7695. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7696. return 'fail'
  7697. # Register recent file
  7698. self.file_opened.emit("gerber", filename)
  7699. # GUI feedback
  7700. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7701. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7702. """
  7703. Opens an Excellon file, parses it and creates a new object for
  7704. it in the program. Thread-safe.
  7705. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7706. :param filename: Excellon file filename
  7707. :type filename: str
  7708. :param plot: boolean, to plot or not the resulting object
  7709. :param from_tcl: True if run from Tcl Shell
  7710. :return: None
  7711. """
  7712. App.log.debug("open_excellon()")
  7713. # How the object should be initialized
  7714. def obj_init(excellon_obj, app_obj):
  7715. try:
  7716. ret = excellon_obj.parse_file(filename=filename)
  7717. if ret == "fail":
  7718. log.debug("Excellon parsing failed.")
  7719. self.inform.emit('[ERROR_NOTCL] %s' %
  7720. _("This is not Excellon file."))
  7721. return "fail"
  7722. except IOError:
  7723. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7724. (_("Cannot open file"), filename))
  7725. log.debug("Could not open Excellon object.")
  7726. return "fail"
  7727. except Exception:
  7728. msg = '[ERROR_NOTCL] %s' % \
  7729. _("An internal error has occurred. See shell.\n")
  7730. msg += traceback.format_exc()
  7731. app_obj.inform.emit(msg)
  7732. return "fail"
  7733. ret = excellon_obj.create_geometry()
  7734. if ret == 'fail':
  7735. log.debug("Could not create geometry for Excellon object.")
  7736. return "fail"
  7737. for tool in excellon_obj.tools:
  7738. if excellon_obj.tools[tool]['solid_geometry']:
  7739. return
  7740. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7741. return "fail"
  7742. with self.proc_container.new(_("Opening Excellon.")):
  7743. # Object name
  7744. name = outname or filename.split('/')[-1].split('\\')[-1]
  7745. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7746. if ret_val == 'fail':
  7747. if from_tcl:
  7748. filename = self.defaults['global_tcl_path'] + '/' + name
  7749. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7750. if ret_val == 'fail':
  7751. self.inform.emit('[ERROR_NOTCL] %s' %
  7752. _('Open Excellon file failed. Probable not an Excellon file.'))
  7753. return
  7754. # Register recent file
  7755. self.file_opened.emit("excellon", filename)
  7756. # GUI feedback
  7757. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7758. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7759. """
  7760. Opens a G-gcode file, parses it and creates a new object for
  7761. it in the program. Thread-safe.
  7762. :param filename: G-code file filename
  7763. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7764. :param force_parsing:
  7765. :param plot: If True plot the object on canvas
  7766. :param from_tcl: True if run from Tcl Shell
  7767. :return: None
  7768. """
  7769. App.log.debug("open_gcode()")
  7770. # How the object should be initialized
  7771. def obj_init(job_obj, app_obj_):
  7772. """
  7773. :param job_obj: the resulting object
  7774. :type app_obj_: App
  7775. """
  7776. assert isinstance(app_obj_, App), \
  7777. "Initializer expected App, got %s" % type(app_obj_)
  7778. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7779. try:
  7780. f = open(filename)
  7781. gcode = f.read()
  7782. f.close()
  7783. except IOError:
  7784. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7785. return "fail"
  7786. job_obj.gcode = gcode
  7787. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7788. if gcode_ret == "fail":
  7789. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7790. return "fail"
  7791. job_obj.create_geometry()
  7792. with self.proc_container.new(_("Opening G-Code.")):
  7793. # Object name
  7794. name = outname or filename.split('/')[-1].split('\\')[-1]
  7795. # New object creation and file processing
  7796. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7797. if ret_val == 'fail':
  7798. if from_tcl:
  7799. filename = self.defaults['global_tcl_path'] + '/' + name
  7800. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7801. if ret_val == 'fail':
  7802. self.inform.emit('[ERROR_NOTCL] %s' %
  7803. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7804. "Try to load it from File menu.\n "
  7805. "Attempting to create a FlatCAM CNCJob Object from "
  7806. "G-Code file failed during processing"))
  7807. return "fail"
  7808. # Register recent file
  7809. self.file_opened.emit("cncjob", filename)
  7810. # GUI feedback
  7811. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7812. def open_hpgl2(self, filename, outname=None):
  7813. """
  7814. Opens a HPGL2 file, parses it and creates a new object for
  7815. it in the program. Thread-safe.
  7816. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7817. :param filename: HPGL2 file filename
  7818. :return: None
  7819. """
  7820. filename = filename
  7821. # How the object should be initialized
  7822. def obj_init(geo_obj, app_obj):
  7823. assert isinstance(geo_obj, GeometryObject), \
  7824. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7825. # Opening the file happens here
  7826. obj = HPGL2(self)
  7827. try:
  7828. HPGL2.parse_file(obj, filename)
  7829. except IOError:
  7830. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7831. return "fail"
  7832. except ParseError as err:
  7833. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7834. app_obj.log.error(str(err))
  7835. return "fail"
  7836. except Exception as e:
  7837. log.debug("App.open_hpgl2() --> %s" % str(e))
  7838. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7839. msg += traceback.format_exc()
  7840. app_obj.inform.emit(msg)
  7841. return "fail"
  7842. geo_obj.multigeo = True
  7843. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7844. geo_obj.tools = deepcopy(obj.tools)
  7845. geo_obj.source_file = deepcopy(obj.source_file)
  7846. del obj
  7847. if not geo_obj.solid_geometry:
  7848. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7849. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7850. return "fail"
  7851. App.log.debug("open_hpgl2()")
  7852. with self.proc_container.new(_("Opening HPGL2")):
  7853. # Object name
  7854. name = outname or filename.split('/')[-1].split('\\')[-1]
  7855. # # ## Object creation # ##
  7856. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7857. if ret == 'fail':
  7858. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7859. return 'fail'
  7860. # Register recent file
  7861. self.file_opened.emit("geometry", filename)
  7862. # GUI feedback
  7863. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7864. def open_script(self, filename, outname=None, silent=False):
  7865. """
  7866. Opens a Script file, parses it and creates a new object for
  7867. it in the program. Thread-safe.
  7868. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7869. :param filename: Script file filename
  7870. :param silent: If True there will be no messages printed to StatusBar
  7871. :return: None
  7872. """
  7873. def obj_init(script_obj, app_obj):
  7874. assert isinstance(script_obj, ScriptObject), \
  7875. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7876. if silent is False:
  7877. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7878. try:
  7879. script_obj.parse_file(filename)
  7880. except IOError:
  7881. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7882. return "fail"
  7883. except ParseError as err:
  7884. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7885. app_obj.log.error(str(err))
  7886. return "fail"
  7887. except Exception as e:
  7888. log.debug("App.open_script() -> %s" % str(e))
  7889. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7890. msg += traceback.format_exc()
  7891. app_obj.inform.emit(msg)
  7892. return "fail"
  7893. App.log.debug("open_script()")
  7894. with self.proc_container.new(_("Opening TCL Script...")):
  7895. # Object name
  7896. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7897. # Object creation
  7898. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7899. if ret_val == 'fail':
  7900. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7901. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7902. if ret_val == 'fail':
  7903. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7904. return 'fail'
  7905. # Register recent file
  7906. self.file_opened.emit("script", filename)
  7907. # GUI feedback
  7908. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7909. def open_config_file(self, filename, run_from_arg=None):
  7910. """
  7911. Loads a config file from the specified file.
  7912. :param filename: Name of the file from which to load.
  7913. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7914. :return: None
  7915. """
  7916. App.log.debug("Opening config file: " + filename)
  7917. if run_from_arg:
  7918. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7919. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7920. _("Opening FlatCAM Config file.")),
  7921. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7922. color=QtGui.QColor("gray"))
  7923. # # add the tab if it was closed
  7924. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7925. # # first clear previous text in text editor (if any)
  7926. # self.ui.text_editor_tab.code_editor.clear()
  7927. #
  7928. # # Switch plot_area to CNCJob tab
  7929. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7930. # close the Code editor if already open
  7931. if self.toggle_codeeditor:
  7932. self.on_toggle_code_editor()
  7933. self.on_toggle_code_editor()
  7934. try:
  7935. if filename:
  7936. f = QtCore.QFile(filename)
  7937. if f.open(QtCore.QIODevice.ReadOnly):
  7938. stream = QtCore.QTextStream(f)
  7939. code_edited = stream.readAll()
  7940. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7941. f.close()
  7942. except IOError:
  7943. App.log.error("Failed to open config file: %s" % filename)
  7944. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7945. (_("Failed to open config file"), filename))
  7946. return
  7947. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7948. """
  7949. Loads a project from the specified file.
  7950. 1) Loads and parses file
  7951. 2) Registers the file as recently opened.
  7952. 3) Calls on_file_new()
  7953. 4) Updates options
  7954. 5) Calls new_object() with the object's from_dict() as init method.
  7955. 6) Calls plot_all() if plot=True
  7956. :param filename: Name of the file from which to load.
  7957. :param run_from_arg: True if run for arguments
  7958. :param plot: If True plot all objects in the project
  7959. :param cli: Run from command line
  7960. :param from_tcl: True if run from Tcl Sehll
  7961. :return: None
  7962. """
  7963. App.log.debug("Opening project: " + filename)
  7964. # block autosaving while a project is loaded
  7965. self.block_autosave = True
  7966. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7967. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7968. if cli is None:
  7969. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7970. if run_from_arg:
  7971. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7972. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7973. _("Opening FlatCAM Project file.")),
  7974. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7975. color=QtGui.QColor("gray"))
  7976. # Open and parse an uncompressed Project file
  7977. try:
  7978. f = open(filename, 'r')
  7979. except IOError:
  7980. if from_tcl:
  7981. name = filename.split('/')[-1].split('\\')[-1]
  7982. filename = self.defaults['global_tcl_path'] + '/' + name
  7983. try:
  7984. f = open(filename, 'r')
  7985. except IOError:
  7986. log.error("Failed to open project file: %s" % filename)
  7987. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7988. return
  7989. else:
  7990. log.error("Failed to open project file: %s" % filename)
  7991. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7992. return
  7993. try:
  7994. d = json.load(f, object_hook=dict2obj)
  7995. except Exception as e:
  7996. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7997. (filename, str(e)))
  7998. f.close()
  7999. # Open and parse a compressed Project file
  8000. try:
  8001. with lzma.open(filename) as f:
  8002. file_content = f.read().decode('utf-8')
  8003. d = json.loads(file_content, object_hook=dict2obj)
  8004. except Exception as e:
  8005. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8006. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8007. return
  8008. # Clear the current project
  8009. # # NOT THREAD SAFE # ##
  8010. if run_from_arg is True:
  8011. pass
  8012. elif cli is True:
  8013. self.delete_selection_shape()
  8014. else:
  8015. self.on_file_new()
  8016. # Project options
  8017. self.options.update(d['options'])
  8018. self.project_filename = filename
  8019. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8020. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8021. if cli is None:
  8022. self.set_screen_units(self.options["units"])
  8023. # Re create objects
  8024. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8025. for obj in d['objs']:
  8026. try:
  8027. def obj_init(obj_inst, app_inst):
  8028. obj_inst.from_dict(obj)
  8029. App.log.debug("Recreating from opened project an %s object: %s" %
  8030. (obj['kind'].capitalize(), obj['options']['name']))
  8031. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8032. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8033. if cli is None:
  8034. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8035. obj['kind'].upper(),
  8036. obj['options']['name']
  8037. )
  8038. )
  8039. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8040. except Exception as e:
  8041. print('App.open_project() --> ' + str(e))
  8042. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8043. self.should_we_save = False
  8044. self.file_opened.emit("project", filename)
  8045. # restore autosaving after a project was loaded
  8046. self.block_autosave = False
  8047. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8048. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8049. if cli is None:
  8050. self.set_ui_title(name=self.project_filename)
  8051. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8052. def plot_all(self, fit_view=True, use_thread=True):
  8053. """
  8054. Re-generates all plots from all objects.
  8055. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8056. :param use_thread: if True will use threading for plotting the objects
  8057. :return: None
  8058. """
  8059. self.log.debug("Plot_all()")
  8060. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8061. for plot_obj in self.collection.get_list():
  8062. def worker_task(obj):
  8063. with self.proc_container.new("Plotting"):
  8064. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8065. if fit_view is True:
  8066. self.object_plotted.emit(obj)
  8067. if use_thread is True:
  8068. # Send to worker
  8069. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8070. else:
  8071. worker_task(plot_obj)
  8072. def register_folder(self, filename):
  8073. """
  8074. Register the last folder used by the app to open something
  8075. :param filename: the last folder is extracted from the filename
  8076. :return: None
  8077. """
  8078. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8079. def register_save_folder(self, filename):
  8080. """
  8081. Register the last folder used by the app to save something
  8082. :param filename: the last folder is extracted from the filename
  8083. :return: None
  8084. """
  8085. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8086. # def set_progress_bar(self, percentage, text=""):
  8087. # """
  8088. # Set a progress bar to a value (percentage)
  8089. #
  8090. # :param percentage: Value set to the progressbar
  8091. # :param text: Not used
  8092. # :return: None
  8093. # """
  8094. # self.ui.progress_bar.setValue(int(percentage))
  8095. def setup_recent_items(self):
  8096. """
  8097. Setup a dictionary with the recent files accessed, organized by type
  8098. :return:
  8099. """
  8100. icons = {
  8101. "gerber": self.resource_location + "/flatcam_icon16.png",
  8102. "excellon": self.resource_location + "/drill16.png",
  8103. 'geometry': self.resource_location + "/geometry16.png",
  8104. "cncjob": self.resource_location + "/cnc16.png",
  8105. "script": self.resource_location + "/script_new24.png",
  8106. "document": self.resource_location + "/notes16_1.png",
  8107. "project": self.resource_location + "/project16.png",
  8108. "svg": self.resource_location + "/geometry16.png",
  8109. "dxf": self.resource_location + "/dxf16.png",
  8110. "pdf": self.resource_location + "/pdf32.png",
  8111. "image": self.resource_location + "/image16.png"
  8112. }
  8113. try:
  8114. image_opener = self.image_tool.import_image
  8115. except AttributeError:
  8116. image_opener = None
  8117. openers = {
  8118. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8119. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8120. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8121. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8122. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8123. "document": None,
  8124. 'project': self.open_project,
  8125. 'svg': self.import_svg,
  8126. 'dxf': self.import_dxf,
  8127. 'image': image_opener,
  8128. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8129. }
  8130. # Open recent file for files
  8131. try:
  8132. f = open(self.data_path + '/recent.json')
  8133. except IOError:
  8134. App.log.error("Failed to load recent item list.")
  8135. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8136. return
  8137. try:
  8138. self.recent = json.load(f)
  8139. except json.errors.JSONDecodeError:
  8140. App.log.error("Failed to parse recent item list.")
  8141. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8142. f.close()
  8143. return
  8144. f.close()
  8145. # Open recent file for projects
  8146. try:
  8147. fp = open(self.data_path + '/recent_projects.json')
  8148. except IOError:
  8149. App.log.error("Failed to load recent project item list.")
  8150. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8151. return
  8152. try:
  8153. self.recent_projects = json.load(fp)
  8154. except json.errors.JSONDecodeError:
  8155. App.log.error("Failed to parse recent project item list.")
  8156. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8157. fp.close()
  8158. return
  8159. fp.close()
  8160. # Closure needed to create callbacks in a loop.
  8161. # Otherwise late binding occurs.
  8162. def make_callback(func, fname):
  8163. def opener():
  8164. func(fname)
  8165. return opener
  8166. def reset_recent_files():
  8167. # Reset menu
  8168. self.ui.recent.clear()
  8169. self.recent = []
  8170. try:
  8171. ff = open(self.data_path + '/recent.json', 'w')
  8172. except IOError:
  8173. App.log.error("Failed to open recent items file for writing.")
  8174. return
  8175. json.dump(self.recent, ff)
  8176. def reset_recent_projects():
  8177. # Reset menu
  8178. self.ui.recent_projects.clear()
  8179. self.recent_projects = []
  8180. try:
  8181. frp = open(self.data_path + '/recent_projects.json', 'w')
  8182. except IOError:
  8183. App.log.error("Failed to open recent projects items file for writing.")
  8184. return
  8185. json.dump(self.recent, frp)
  8186. # Reset menu
  8187. self.ui.recent.clear()
  8188. self.ui.recent_projects.clear()
  8189. # Create menu items for projects
  8190. for recent in self.recent_projects:
  8191. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8192. if recent['kind'] == 'project':
  8193. try:
  8194. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8195. # Attach callback
  8196. o = make_callback(openers[recent["kind"]], recent['filename'])
  8197. action.triggered.connect(o)
  8198. self.ui.recent_projects.addAction(action)
  8199. except KeyError:
  8200. App.log.error("Unsupported file type: %s" % recent["kind"])
  8201. # Last action in Recent Files menu is one that Clear the content
  8202. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8203. (_("Clear Recent projects")), self)
  8204. clear_action_proj.triggered.connect(reset_recent_projects)
  8205. self.ui.recent_projects.addSeparator()
  8206. self.ui.recent_projects.addAction(clear_action_proj)
  8207. # Create menu items for files
  8208. for recent in self.recent:
  8209. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8210. if recent['kind'] != 'project':
  8211. try:
  8212. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8213. # Attach callback
  8214. o = make_callback(openers[recent["kind"]], recent['filename'])
  8215. action.triggered.connect(o)
  8216. self.ui.recent.addAction(action)
  8217. except KeyError:
  8218. App.log.error("Unsupported file type: %s" % recent["kind"])
  8219. # Last action in Recent Files menu is one that Clear the content
  8220. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8221. (_("Clear Recent files")), self)
  8222. clear_action.triggered.connect(reset_recent_files)
  8223. self.ui.recent.addSeparator()
  8224. self.ui.recent.addAction(clear_action)
  8225. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8226. # self.ui.menufilerecent.set_submenu(recent_menu)
  8227. # recent_menu.show_all()
  8228. # self.ui.recent.show()
  8229. self.log.debug("Recent items list has been populated.")
  8230. def setup_component_editor(self):
  8231. """
  8232. Default text for the Selected tab when is not taken by the Object UI.
  8233. :return:
  8234. """
  8235. # label = QtWidgets.QLabel("Choose an item from Project")
  8236. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8237. sel_title = QtWidgets.QTextEdit(
  8238. _('<b>Shortcut Key List</b>'))
  8239. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8240. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8241. f_settings = QSettings("Open Source", "FlatCAM")
  8242. if f_settings.contains("notebook_font_size"):
  8243. fsize = f_settings.value('notebook_font_size', type=int)
  8244. else:
  8245. fsize = 12
  8246. tsize = fsize + int(fsize / 2)
  8247. # selected_text = (_('''
  8248. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8249. # </p>
  8250. #
  8251. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8252. # The normal flow when working in FlatCAM is the following:</span></p>
  8253. #
  8254. # <ol>
  8255. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8256. # file into
  8257. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8258. # even dragging and dropping the files on the GUI.<br />
  8259. # <br />
  8260. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8261. # drop of the
  8262. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8263. # &nbsp;</li>
  8264. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8265. # and then
  8266. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8267. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8268. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8269. # <br />
  8270. # If the selection of the object is done on the canvas by single click instead, and the
  8271. # <strong>SELECTED TAB</strong>
  8272. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8273. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8274. # it even if it was out of focus.<br />
  8275. # <br />
  8276. # You can change the parameters in this screen and the flow direction is like this:<br />
  8277. # <br />
  8278. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8279. # <strong> Geometry Object
  8280. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8281. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8282. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8283. # </ol>
  8284. #
  8285. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8286. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8287. # <strong>F3</strong>.</span></p>
  8288. #
  8289. # ''').format(fsize=fsize, tsize=tsize))
  8290. selected_text = '''
  8291. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8292. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8293. {s1}</span></p>
  8294. <ol>
  8295. <li><span style="font-size:{fsize}px">{s2}<br />
  8296. <br />
  8297. {s3}</span><br />
  8298. &nbsp;</li>
  8299. <li><span style="font-size:{fsize}px">{s4}<br />
  8300. &nbsp;</li>
  8301. <br />
  8302. <li><span style="font-size:{fsize}px">{s5}<br />
  8303. &nbsp;</li>
  8304. <br />
  8305. <li><span style="font-size:{fsize}px">{s6}<br />
  8306. <br />
  8307. {s7}</span></li>
  8308. </ol>
  8309. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8310. '''.format(
  8311. title=_("Selected Tab - Choose an Item from Project Tab"),
  8312. subtitle=_("Details"),
  8313. s1=_("The normal flow when working in FlatCAM is the following:"),
  8314. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8315. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8316. "files on the GUI."),
  8317. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8318. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8319. "actions offered within the app."),
  8320. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8321. "on 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 its kind: "
  8323. "Gerber, Excellon, Geometry or CNCJob object."),
  8324. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8325. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8326. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8327. "the SELECTED TAB and populate it even if it was out of focus."),
  8328. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8329. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8330. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8331. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8332. "(again, done in SELECTED TAB) --> Save GCode."),
  8333. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8334. "or through its own key shortcut: <b>F3</b>."),
  8335. tsize=tsize,
  8336. fsize=fsize
  8337. )
  8338. sel_title.setText(selected_text)
  8339. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8340. self.ui.selected_scroll_area.setWidget(sel_title)
  8341. def setup_obj_classes(self):
  8342. """
  8343. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8344. class.
  8345. :return: None
  8346. """
  8347. FlatCAMObj.app = self
  8348. ObjectCollection.app = self
  8349. Gerber.app = self
  8350. Excellon.app = self
  8351. Geometry.app = self
  8352. CNCjob.app = self
  8353. FCProcess.app = self
  8354. FCProcessContainer.app = self
  8355. OptionsGroupUI.app = self
  8356. def version_check(self):
  8357. """
  8358. Checks for the latest version of the program. Alerts the
  8359. user if theirs is outdated. This method is meant to be run
  8360. in a separate thread.
  8361. :return: None
  8362. """
  8363. self.log.debug("version_check()")
  8364. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8365. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8366. App.version_url,
  8367. str(self.defaults['global_serial']),
  8368. str(self.version),
  8369. str(self.os),
  8370. urllib.parse.urlencode(self.defaults["global_stats"])
  8371. )
  8372. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8373. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8374. # urllib.parse.urlencode(self.defaults["global_stats"])
  8375. else:
  8376. # no_stats dict; just so it won't break things on website
  8377. no_ststs_dict = {}
  8378. no_ststs_dict["global_ststs"] = {}
  8379. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8380. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8381. App.log.debug("Checking for updates @ %s" % full_url)
  8382. # ## Get the data
  8383. try:
  8384. f = urllib.request.urlopen(full_url)
  8385. except Exception:
  8386. # App.log.warning("Failed checking for latest version. Could not connect.")
  8387. self.log.warning("Failed checking for latest version. Could not connect.")
  8388. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8389. return
  8390. try:
  8391. data = json.load(f)
  8392. except Exception as e:
  8393. App.log.error("Could not parse information about latest version.")
  8394. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8395. App.log.debug("json.load(): %s" % str(e))
  8396. f.close()
  8397. return
  8398. f.close()
  8399. # ## Latest version?
  8400. if self.version >= data["version"]:
  8401. App.log.debug("FlatCAM is up to date!")
  8402. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8403. return
  8404. App.log.debug("Newer version available.")
  8405. self.message.emit(
  8406. _("Newer Version Available"),
  8407. '%s<br><br>><b>%s</b><br>%s' % (
  8408. _("There is a newer version of FlatCAM available for download:"),
  8409. str(data["name"]),
  8410. str(data["message"])
  8411. ),
  8412. _("info")
  8413. )
  8414. def on_plotcanvas_setup(self, container=None):
  8415. """
  8416. This is doing the setup for the plot area (canvas).
  8417. :param container: QT Widget where to install the canvas
  8418. :return: None
  8419. """
  8420. if container:
  8421. plot_container = container
  8422. else:
  8423. plot_container = self.ui.right_layout
  8424. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8425. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8426. self.is_legacy = True
  8427. self.defaults["global_graphic_engine"] = "2D"
  8428. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8429. else:
  8430. try:
  8431. self.plotcanvas = PlotCanvas(plot_container, self)
  8432. except Exception as er:
  8433. msg_txt = traceback.format_exc()
  8434. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8435. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8436. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8437. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8438. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8439. msg += msg_txt
  8440. self.inform.emit(msg)
  8441. return 'fail'
  8442. # So it can receive key presses
  8443. self.plotcanvas.native.setFocus()
  8444. if self.is_legacy is False:
  8445. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8446. # Set the mouse button for panning
  8447. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8448. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8449. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8450. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8451. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8452. # Keys over plot enabled
  8453. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8454. if self.defaults['global_cursor_type'] == 'small':
  8455. self.app_cursor = self.plotcanvas.new_cursor()
  8456. else:
  8457. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8458. if self.ui.grid_snap_btn.isChecked():
  8459. self.app_cursor.enabled = True
  8460. else:
  8461. self.app_cursor.enabled = False
  8462. if self.is_legacy is False:
  8463. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8464. else:
  8465. # will use the default Matplotlib axes
  8466. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8467. def on_zoom_fit(self, event):
  8468. """
  8469. Callback for zoom-fit request. This can be either from the corresponding
  8470. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8471. with axes limits from the geometry bounds of all objects.
  8472. :param event: Ignored.
  8473. :return: None
  8474. """
  8475. if self.is_legacy is False:
  8476. self.plotcanvas.fit_view()
  8477. else:
  8478. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8479. width = xmax - xmin
  8480. height = ymax - ymin
  8481. xmin -= 0.05 * width
  8482. xmax += 0.05 * width
  8483. ymin -= 0.05 * height
  8484. ymax += 0.05 * height
  8485. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8486. def on_zoom_in(self):
  8487. """
  8488. Callback for zoom-in request.
  8489. :return:
  8490. """
  8491. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8492. def on_zoom_out(self):
  8493. """
  8494. Callback for zoom-out request.
  8495. :return:
  8496. """
  8497. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8498. def disable_all_plots(self):
  8499. self.defaults.report_usage("disable_all_plots()")
  8500. self.disable_plots(self.collection.get_list())
  8501. self.inform.emit('[success] %s' %
  8502. _("All plots disabled."))
  8503. def disable_other_plots(self):
  8504. self.defaults.report_usage("disable_other_plots()")
  8505. self.disable_plots(self.collection.get_non_selected())
  8506. self.inform.emit('[success] %s' %
  8507. _("All non selected plots disabled."))
  8508. def enable_all_plots(self):
  8509. self.defaults.report_usage("enable_all_plots()")
  8510. self.enable_plots(self.collection.get_list())
  8511. self.inform.emit('[success] %s' %
  8512. _("All plots enabled."))
  8513. def on_enable_sel_plots(self):
  8514. log.debug("App.on_enable_sel_plot()")
  8515. object_list = self.collection.get_selected()
  8516. self.enable_plots(objects=object_list)
  8517. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8518. def on_disable_sel_plots(self):
  8519. log.debug("App.on_disable_sel_plot()")
  8520. # self.inform.emit(_("Disabling plots ..."))
  8521. object_list = self.collection.get_selected()
  8522. self.disable_plots(objects=object_list)
  8523. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8524. def enable_plots(self, objects):
  8525. """
  8526. Enable plots
  8527. :param objects: list of Objects to be enabled
  8528. :return:
  8529. """
  8530. log.debug("Enabling plots ...")
  8531. # self.inform.emit(_("Working ..."))
  8532. for obj in objects:
  8533. if obj.options['plot'] is False:
  8534. obj.options.set_change_callback(lambda x: None)
  8535. obj.options['plot'] = True
  8536. try:
  8537. # only the Gerber obj has on_plot_cb_click() method
  8538. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8539. # disable this cb while disconnected,
  8540. # in case the operation takes time the user is not allowed to change it
  8541. obj.ui.plot_cb.setDisabled(True)
  8542. except AttributeError:
  8543. pass
  8544. obj.set_form_item("plot")
  8545. try:
  8546. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8547. obj.ui.plot_cb.setDisabled(False)
  8548. except AttributeError:
  8549. pass
  8550. obj.options.set_change_callback(obj.on_options_change)
  8551. def worker_task(objs):
  8552. with self.proc_container.new(_("Enabling plots ...")):
  8553. for plot_obj in objs:
  8554. # obj.options['plot'] = True
  8555. if isinstance(plot_obj, CNCJobObject):
  8556. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8557. else:
  8558. plot_obj.plot(visible=True)
  8559. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8560. # self.plots_updated.emit()
  8561. def disable_plots(self, objects):
  8562. """
  8563. Disables plots
  8564. :param objects: list of Objects to be disabled
  8565. :return:
  8566. """
  8567. # if no objects selected then do nothing
  8568. if not self.collection.get_selected():
  8569. return
  8570. log.debug("Disabling plots ...")
  8571. # self.inform.emit(_("Working ..."))
  8572. for obj in objects:
  8573. if obj.options['plot'] is True:
  8574. obj.options.set_change_callback(lambda x: None)
  8575. obj.options['plot'] = False
  8576. try:
  8577. # only the Gerber obj has on_plot_cb_click() method
  8578. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8579. obj.ui.plot_cb.setDisabled(True)
  8580. except AttributeError:
  8581. pass
  8582. obj.set_form_item("plot")
  8583. try:
  8584. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8585. obj.ui.plot_cb.setDisabled(False)
  8586. except AttributeError:
  8587. pass
  8588. obj.options.set_change_callback(obj.on_options_change)
  8589. try:
  8590. self.delete_selection_shape()
  8591. except Exception as e:
  8592. log.debug("App.disable_plots() --> %s" % str(e))
  8593. # self.plots_updated.emit()
  8594. def worker_task(objs):
  8595. with self.proc_container.new(_("Disabling plots ...")):
  8596. for plot_obj in objs:
  8597. # obj.options['plot'] = True
  8598. if isinstance(plot_obj, CNCJobObject):
  8599. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8600. else:
  8601. plot_obj.plot(visible=False)
  8602. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8603. def toggle_plots(self, objects):
  8604. """
  8605. Toggle plots visibility
  8606. :param objects: list of Objects for which to be toggled the visibility
  8607. :return: None
  8608. """
  8609. # if no objects selected then do nothing
  8610. if not self.collection.get_selected():
  8611. return
  8612. log.debug("Toggling plots ...")
  8613. self.inform.emit(_("Working ..."))
  8614. for obj in objects:
  8615. if obj.options['plot'] is False:
  8616. obj.options['plot'] = True
  8617. else:
  8618. obj.options['plot'] = False
  8619. self.plots_updated.emit()
  8620. def clear_plots(self):
  8621. """
  8622. Clear the plots
  8623. :return: None
  8624. """
  8625. objects = self.collection.get_list()
  8626. for obj in objects:
  8627. obj.clear(obj == objects[-1])
  8628. # Clear pool to free memory
  8629. self.clear_pool()
  8630. def on_set_color_action_triggered(self):
  8631. """
  8632. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8633. :return:
  8634. """
  8635. new_color = self.defaults['gerber_plot_fill']
  8636. clicked_action = self.sender()
  8637. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8638. act_name = clicked_action.text()
  8639. sel_obj_list = self.collection.get_selected()
  8640. if not sel_obj_list:
  8641. return
  8642. # a default value, I just chose this one
  8643. alpha_level = 'BF'
  8644. for sel_obj in sel_obj_list:
  8645. if sel_obj.kind == 'excellon':
  8646. alpha_level = str(hex(
  8647. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8648. elif sel_obj.kind == 'gerber':
  8649. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8650. elif sel_obj.kind == 'geometry':
  8651. alpha_level = 'FF'
  8652. else:
  8653. log.debug(
  8654. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8655. continue
  8656. sel_obj.alpha_level = alpha_level
  8657. if act_name == _('Red'):
  8658. new_color = '#FF0000' + alpha_level
  8659. if act_name == _('Blue'):
  8660. new_color = '#0000FF' + alpha_level
  8661. if act_name == _('Yellow'):
  8662. new_color = '#FFDF00' + alpha_level
  8663. if act_name == _('Green'):
  8664. new_color = '#00FF00' + alpha_level
  8665. if act_name == _('Purple'):
  8666. new_color = '#FF00FF' + alpha_level
  8667. if act_name == _('Brown'):
  8668. new_color = '#A52A2A' + alpha_level
  8669. if act_name == _('White'):
  8670. new_color = '#FFFFFF' + alpha_level
  8671. if act_name == _('Black'):
  8672. new_color = '#000000' + alpha_level
  8673. if act_name == _('Custom'):
  8674. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8675. c_dialog = QtWidgets.QColorDialog()
  8676. plot_fill_color = c_dialog.getColor(initial=new_color)
  8677. if plot_fill_color.isValid() is False:
  8678. return
  8679. new_color = str(plot_fill_color.name()) + alpha_level
  8680. if act_name == _("Default"):
  8681. for sel_obj in sel_obj_list:
  8682. if sel_obj.kind == 'excellon':
  8683. new_color = self.defaults['excellon_plot_fill']
  8684. new_line_color = self.defaults['excellon_plot_line']
  8685. elif sel_obj.kind == 'gerber':
  8686. new_color = self.defaults['gerber_plot_fill']
  8687. new_line_color = self.defaults['gerber_plot_line']
  8688. elif sel_obj.kind == 'geometry':
  8689. new_color = self.defaults['geometry_plot_line']
  8690. new_line_color = self.defaults['geometry_plot_line']
  8691. else:
  8692. log.debug(
  8693. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8694. continue
  8695. sel_obj.fill_color = new_color
  8696. sel_obj.outline_color = new_line_color
  8697. sel_obj.shapes.redraw(
  8698. update_colors=(new_color, new_line_color)
  8699. )
  8700. return
  8701. if act_name == _("Opacity"):
  8702. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8703. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8704. if ok_button:
  8705. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8706. for sel_obj in sel_obj_list:
  8707. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8708. sel_obj.shapes.redraw(
  8709. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8710. )
  8711. return
  8712. new_line_color = color_variant(new_color[:7], 0.7)
  8713. if act_name == _("White"):
  8714. new_line_color = color_variant("#dedede", 0.7)
  8715. for sel_obj in sel_obj_list:
  8716. sel_obj.fill_color = new_color
  8717. sel_obj.outline_color = new_line_color
  8718. sel_obj.shapes.redraw(
  8719. update_colors=(new_color, new_line_color)
  8720. )
  8721. def generate_cnc_job(self, objects):
  8722. """
  8723. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8724. :param objects: Selected objects in the Project Tab
  8725. :return:
  8726. """
  8727. self.defaults.report_usage("generate_cnc_job()")
  8728. # for obj in objects:
  8729. # obj.generatecncjob()
  8730. for obj in objects:
  8731. obj.on_generatecnc_button_click()
  8732. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8733. """
  8734. Saves the current project to the specified file.
  8735. :param filename: Name of the file in which to save.
  8736. :type filename: str
  8737. :param quit_action: if the project saving will be followed by an app quit; boolean
  8738. :param silent: if True will not display status messages
  8739. :param from_tcl True is run from Tcl Shell
  8740. :return: None
  8741. """
  8742. self.log.debug("save_project()")
  8743. self.save_in_progress = True
  8744. with self.proc_container.new(_("Saving FlatCAM Project")):
  8745. # Capture the latest changes
  8746. # Current object
  8747. try:
  8748. current_object = self.collection.get_active()
  8749. if current_object:
  8750. current_object.read_form()
  8751. except Exception as e:
  8752. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8753. pass
  8754. # Serialize the whole project
  8755. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8756. "options": self.options,
  8757. "version": self.version}
  8758. if self.defaults["global_save_compressed"] is True:
  8759. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8760. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8761. # # Write
  8762. f.write(g)
  8763. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8764. else:
  8765. # Open file
  8766. try:
  8767. f = open(filename, 'w')
  8768. except IOError:
  8769. App.log.error("Failed to open file for saving: %s", filename)
  8770. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8771. return
  8772. # Write
  8773. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8774. f.close()
  8775. # verification of the saved project
  8776. # Open and parse
  8777. try:
  8778. saved_f = open(filename, 'r')
  8779. except IOError:
  8780. if silent is False:
  8781. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8782. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8783. return
  8784. try:
  8785. saved_d = json.load(saved_f, object_hook=dict2obj)
  8786. except Exception:
  8787. if silent is False:
  8788. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8789. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8790. f.close()
  8791. return
  8792. saved_f.close()
  8793. if silent is False:
  8794. if 'version' in saved_d:
  8795. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8796. else:
  8797. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8798. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8799. tb_settings = QSettings("Open Source", "FlatCAM")
  8800. lock_state = self.ui.lock_action.isChecked()
  8801. tb_settings.setValue('toolbar_lock', lock_state)
  8802. # This will write the setting to the platform specific storage.
  8803. del tb_settings
  8804. # if quit:
  8805. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8806. # t.start()
  8807. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8808. def start_delayed_quit(self, delay, filename, should_quit=None):
  8809. """
  8810. :param delay: period of checking if project file size is more than zero; in seconds
  8811. :param filename: the name of the project file to be checked periodically for size more than zero
  8812. :param should_quit: if the task finished will be followed by an app quit; boolean
  8813. :return:
  8814. """
  8815. to_quit = should_quit
  8816. self.save_timer = QtCore.QTimer()
  8817. self.save_timer.setInterval(delay)
  8818. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8819. self.save_timer.start()
  8820. def check_project_file_size(self, filename, should_quit=None):
  8821. """
  8822. :param filename: the name of the project file to be checked periodically for size more than zero
  8823. :param should_quit: will quit the app if True; boolean
  8824. :return:
  8825. """
  8826. try:
  8827. if os.stat(filename).st_size > 0:
  8828. self.save_in_progress = False
  8829. self.save_timer.stop()
  8830. if should_quit:
  8831. self.app_quit.emit()
  8832. except Exception:
  8833. traceback.print_exc()
  8834. def save_project_auto(self):
  8835. """
  8836. Called periodically to save the project.
  8837. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8838. # progress.
  8839. :return:
  8840. """
  8841. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8842. self.on_file_saveproject()
  8843. def save_project_auto_update(self):
  8844. """
  8845. Update the auto save time interval value.
  8846. :return:
  8847. """
  8848. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8849. try:
  8850. if self.autosave_timer.isActive():
  8851. self.autosave_timer.stop()
  8852. except Exception:
  8853. pass
  8854. if self.defaults['global_autosave'] is True:
  8855. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8856. self.autosave_timer.start()
  8857. def on_options_app2project(self):
  8858. """
  8859. Callback for Options->Transfer Options->App=>Project. Copies options
  8860. from application defaults to project defaults.
  8861. :return: None
  8862. """
  8863. self.defaults.report_usage("on_options_app2project")
  8864. self.preferencesUiManager.defaults_read_form()
  8865. self.options.update(self.defaults)
  8866. def toggle_shell(self):
  8867. """
  8868. Toggle shell: if is visible close it, if it is closed then open it
  8869. :return: None
  8870. """
  8871. self.defaults.report_usage("toggle_shell()")
  8872. if self.ui.shell_dock.isVisible():
  8873. self.ui.shell_dock.hide()
  8874. self.plotcanvas.native.setFocus()
  8875. else:
  8876. self.ui.shell_dock.show()
  8877. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8878. # self.shell._edit.setFocus()
  8879. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8880. # HACK - simulate a mouse click - alternative
  8881. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8882. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8883. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8884. # no_km)
  8885. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8886. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8887. # no_km)
  8888. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8889. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8890. """
  8891. Shows a message on the FlatCAM Shell
  8892. :param msg: Message to display.
  8893. :param show: Opens the shell.
  8894. :param error: Shows the message as an error.
  8895. :param warning: Shows the message as an warning.
  8896. :param success: Shows the message as an success.
  8897. :param selected: Indicate that something was selected on canvas
  8898. :return: None
  8899. """
  8900. if show:
  8901. self.ui.shell_dock.show()
  8902. try:
  8903. if error:
  8904. self.shell.append_error(msg + "\n")
  8905. elif warning:
  8906. self.shell.append_warning(msg + "\n")
  8907. elif success:
  8908. self.shell.append_success(msg + "\n")
  8909. elif selected:
  8910. self.shell.append_selected(msg + "\n")
  8911. else:
  8912. self.shell.append_output(msg + "\n")
  8913. except AttributeError:
  8914. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8915. class ArgsThread(QtCore.QObject):
  8916. open_signal = pyqtSignal(list)
  8917. start = pyqtSignal()
  8918. stop = pyqtSignal()
  8919. if sys.platform == 'win32':
  8920. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8921. else:
  8922. address = ('/tmp/testipc', 'AF_UNIX')
  8923. def __init__(self):
  8924. super(ArgsThread, self).__init__()
  8925. self.listener = None
  8926. self.thread_exit = False
  8927. self.start.connect(self.run)
  8928. self.stop.connect(self.close_listener)
  8929. def my_loop(self, address):
  8930. try:
  8931. self.listener = Listener(*address)
  8932. while self.thread_exit is False:
  8933. conn = self.listener.accept()
  8934. self.serve(conn)
  8935. except socket.error:
  8936. try:
  8937. conn = Client(*address)
  8938. conn.send(sys.argv)
  8939. conn.send('close')
  8940. # close the current instance only if there are args
  8941. if len(sys.argv) > 1:
  8942. try:
  8943. self.listener.close()
  8944. except Exception:
  8945. pass
  8946. sys.exit()
  8947. except ConnectionRefusedError:
  8948. if sys.platform == 'win32':
  8949. pass
  8950. else:
  8951. os.system('rm /tmp/testipc')
  8952. self.listener = Listener(*address)
  8953. while True:
  8954. conn = self.listener.accept()
  8955. self.serve(conn)
  8956. def serve(self, conn):
  8957. while self.thread_exit is False:
  8958. msg = conn.recv()
  8959. if msg == 'close':
  8960. break
  8961. self.open_signal.emit(msg)
  8962. conn.close()
  8963. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8964. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8965. @pyqtSlot()
  8966. def run(self):
  8967. self.my_loop(self.address)
  8968. @pyqtSlot()
  8969. def close_listener(self):
  8970. self.thread_exit = True
  8971. self.listener.close()
  8972. # end of file